Datasheet
Task 1.7: Use Streams, Pipes, and Redirection
37
requires you to enter text either as a command-line option or via standard input. Thus, you’d
redirect standard input from the error-messages.txt file. You’d also have to redirect stan-
dard output to save the result in a file:
$ text2gif < error-messages.txt > error-graphics.gif
You can use a graphics program, such as the GIMP, to view the error-graphics.gif file
to verify that it contains the correct image.
When using the redirection operators, you start a command line with the pro-
gram name and then “point” the operators toward their destinations—the
input redirection operator points left, toward the command name, whereas
the output redirection operators point right, toward the filename of the file
you want to create.
Piping Data between Programs
The preceding example showed text2gif operating on a file that was created by another pro-
gram. This approach is common in Linux; so common, in fact, that a variant of the redirection
operator exists to simplify matters. This tool is known as a pipe or a pipeline, and it’s a way
to send standard output from one program directly into another, without using any on-disk
file. The symbol for a pipe is a vertical bar (|), located above the Enter key on the same key
that holds the backslash (\) character on most keyboards. You place the pipe character
between the commands. For instance, instead of saving the output of netstat -p in a file and
then examining that file with less, you can pipe the result directly into less:
$ netstat -p | less
Another common use of a pipe is to send the results of a lengthy command through grep,
which searches for lines containing a particular string that you specify. For instance, to search
for the lines in the netstat output that refer to Firefox, you might issue the following command:
$ netstat -p | grep firefox
You can create a pipeline containing multiple commands and even redirect the output of the
final command:
$ netstat -p | grep firefox | text2gif > netstat-output.gif
Additional Pipe and Redirection Tricks
Pipes and redirection can be combined in complex ways and obscure variants may be used. For
instance, the &1 and &2 strings refer to standard output and standard error, respectively. This
fact enables you to pipe standard error without also piping standard output:
$ netstat -p 2>&1 > /dev/null | text2gif > error-message.gif
83484.book Page 37 Monday, September 18, 2006 8:58 AM










