LPI 1Article #5 Pipes, Redirection and Streams


Pipes, Redirection and Streams
In this tutorial, we are going on to look at Streams, Redirection and Streams
These are tools of the command-line that are very powerful in administering the Linux system. As an operating system, Linux handles the input(data from keyboard) and output(data out of the screen) of programs in the manner as streams. In that manner, the streams can therefore be manipulated. It is therefore possible to redirect the inputs and outputs to come from or go to other places. In the same manner, one can pipe the output of one program into another one. Let us now take a look at some of the streams.

Stream Explanation
Standard Input Stream from the keyboard or other input source (stdin). File descriptor is 0
Standard Output Stream of data normally displayed on the screen(stdout). File descriptor is 1
Standard Error Output stream intended to carry high-priority information e.g error messages. File descriptor is 2

The inner working of the system programs treats these streams like mundane files. The programs open these files, read them and finally close them when they have finished with their contents.
Redirecting Input and Output
There are symbols that are used to redirect the inputs or outputs

Redirection symbol The Effect
> This one creates a new file containing standard output or overwrites the existing one
echo $HOSTNAME > name.txt
Creates a file name.txt and writes the contents of HOSTNAME therein or overwrites the existing file.
>> This one appends(adds at the end) the standard output to the file or creates another one
echo $HOSTNAME >> name.txt
Adds the contents of HOSTNAME to name.txt or creates a new file
2> Creates a new file containing standard error or overwrites the specified file
2>> This one appends the standard error to the specified file or creates another file if the specified one is non-existent
&>> The symbol creates a file that contains both the standard error and standard output or overwrites the file f it exists.
< The contents of the specified file are sent to be utilized as standard input
<< The texts on the following lines are to be accepted as standard input
<> The specified file is used both as standard output and standard input

There is another redirection command known as tee. This command splits the standard input in such a manner that is can be displayed on the screen or on any standard output and be stored to other files at the same time.
$ myprog | tee myfile.txt
The command above causes the myprog to be viewed and stored in the myfile.txt file at the same time.


Please enter your comment!
Please enter your name here