Pipes were introduced in the early years of the 1970s by Doug McIlroy. These are streams made by the operating system itself. With pipes, you can redirect the output of one command to the input of another with a simple syntax on the command line. The symbol used for a pipe is |.
For example, below we will sort the first ten lines of a file. For this, we need to give to the sort command only the first ten lines. We will use the head command for this task. We will direct the output of the head command to the input of the sort command with the pipe:
head -10 | sort
The operating system will assure us of the synchronization of the data stream between the two functions. You can use the pipe as many times as you wish on a command line. For instance, you can read in the whole file, sort that and print out the last two lines in a single command line.
Sometimes you may want to save/print to a file the content of a partial result inside a sequence of pipes. For this, you can use the tee function. Its use is simple. After the name of the function, add the name of the file where you want to save the stream. The command will print first to the file and then to the output. For example, let us read, sort, save and print the first item of a file:
cat alfa.txt | sort | tee sorted_alfa.txt | head -1
Sometimes we just want to dump a data stream. If this is the case, we can use the special devices instead of files. A device like this is /dev/null. This is a very greedy device. It will eat up all the character sequences you can throw at it. This is the place where you should direct any data stream that you do not want to use.
A stream like this can be the errors that show up in a command line. The cat command will list the contents of a file unless the file does not exist. If the file does not exist, it will throw an error. You should already know from my previous articles that the standard input is zero, the standard output is one and the standard error is two. With this knowledge in your pocket, the solution looks like this: