After talking about standard output and standard error, we will now encounter a command that makes use of standard input. That command serves many different purposes, and we will try to mention some of them. The command is known as cat (concatenate).
The cat command
The cat command is one of the most commonly used Linux commands. It reads through a file (or more files) and copies them to standard output. It is most useful for displaying the contents of a text file without paging. We used cat already in one of the past articles.
cat some-file.txt # displaying a single file cat some-file1.txt some-file2.txt # displaying multiple files
Cat is most commonly used to quickly display short text files. Additionally, it serves a lot of different functionalities – we can see the content of multiple files in the terminal, display line numbers, sort contents of different files, append contents of one file to another and so on…
But, let us just write cat (without any additional arguments into the terminal). If the argument list is empty, cat will read from the standard input, the standard input is connected to the keyboard, so cat will actually, wait for the user to type something. We can use this behavior to create text files. We can press Ctrl+D to exit the cat command.
cat > cat-input.txt
But, we can also do the reverse! By using the “<“ redirection operator we can change the source of standard input from the keyboard to the file! If we run the command below, we will see that the file has served as a source of standard input. Not very useful, but still applicable as an example to show that a file can be used as a source of standard input.
cat < cat-input.txt
Just to wrap things up regarding the cat command. In (1) we displayed the contents of the bubble-sort.js file (for this blog post click here), then we just typed cat without any arguments, and the command waits for the standard input to write anything! Then in (3) we redirected the standard input to a text file, in (4) we displayed that file, and in (5) we actually changed the source of input to the cat-input.txt file!
Pipelines
We can use a shell feature called pipelines to actually read data from standard input and send it to standard output. The pipeline operator “|” is commonly used for this functionality, and we can pipe the standard output of one command into the standard input of another.
command1 | command2
A command that accepts standard input is less. We can use less to display, page-by-page the output of any command that uses standard output. Using this technique we can examine the output of any command that produces standard output. (We will also mention this in more detail in forthcoming articles!)
ls -l /usr/bin | less
Wrapping it up
This was a simple introduction to the standard input and the cat command. We will see a lot more examples regarding pipelines in the next part. Stay tuned!
While you wait, you can read more Linux related posts here and other blog posts you can find here.