Redirection and Pipes

Working With Unix
[Redirection |Pipes |Exercises ]

Redirection

Put simply, redirection is the redirection of the standard input and output. It allows you to redirect the input, what you would type in, to come from a file. It allows the output, what you would normally see on the screen, to be redirected to a file.

The redirection operator for input is the "<" and the redirection operator for output is the ">." The easy way to remember these is that they are like funnels. The large end takes data, and feeds it to the small end.

command < input_file > output_file
For example, here is a really lame way to copy a file.
larry% cat mp.and.the.holy.grail.txt > mp
The file is displayed to the screen usually, but in this case, the output from cat is redirected into the file mp.

Many commands that usually take their data from file specified on the command line, will take it from standard input when there are no filenames. Sort is one of those.

larry% sort < breakfast
In this example, breakfast is directed into sort as its standard input. The sorted list is displayed to the screen. If you wanted it saved to a file, you could use the "-o" option, or you could redirect the output to a file.

larry% sort dinner

Pipes

Next on the list of great UNIX features like redirection, are pipes. Pipes are a lot like redirection in that they redirect the standard input and output of commands, but with pipes, you redirect the output of one command into the input of another. The symbol for a pipe is the pipe character "|."

A useful example of using a pipe, is to pipe the output of a program to more. If you sorted a really large file, you could do this:

larry% sort mp.and.the.holy.grail.txt | more
This is much better then trying to read as fast as your terminal can output, and
easier than saving the output to a file, and the moring it separately.

You can construct entire pipelines with pipes. To read all of the lines containing the word "the" in a large text file in sorted order, you could do the following:

larry% grep the mp.and.the.holy.grail.txt | sort | more
It can also be useful if you can't remember that commands, like grep, actually take a filename argument because you can use cat to pipe it in:

larry% cat mp.and.the.holy.grail.txt | grep the | wc -l

Exercises

  1. Redirect the output of ls -al to a file.
    larry% ls -al > bomb
    
  2. Redirect a file into grep.
    larry% grep the < mp.and.the.holy.grail.txt
    
  3. Sort a file, and read it through more without using command line options.
    larry% cat mp.and.the.holy.grail.txt | sort | more
    

[Back |Contents |Next ]

Edward B. Schaller (schallee@earthlink.net)