next up previous contents
Next: Process Management Up: Unix Users Introduction Course Previous: Wildcards

Piping & Redirection

Piping and redirection are ways of changing where a program puts its output and from where it takes its input. We have already seen an example of redirection using the cat command. In the examples the cat command took its input from a file or put its output into a file. Piping works in a similar way except that the output of one program is used as the input to another program.

To give a few examples we will use the grepgif program. In its simplest form it will search its input for a string of characters. Say we are looking for a particular file in a very big directory. We know its name contains a 'd'. Using redirectiongif we could first create a file containing all the entries in the directory and then use this file as the input to the grep command:

$ls > our_dir
$cat < our_dir     
a
b
c
d
data
e
junk
our_dir
programs
$grep d < our_dir 
d
data
our_dir
$rm our_dir
$

As this is somewhat cumbersome UNIX also provides us with pipes. These save us having to create a temporary file. To use them we simply put a '|' between the two programs:

$ls|grep d
d
data
$

Piping and redirection can also be mixed and both kinds of redirection used simultaneously. Also piping is not restricted to two programs, but can involve a whole chain of programs. It is for instance possible to take the input from a file ('<'), then grep some information out, grep some more selected information ('|'), then sort the output ('|') and finally write the output into a file ('>').

Whenever we use the '>' symbol the output file is overwritten with our new information. If we want to keep the original output file and just append our new information to it, we can use two '>' symbols:

$cat > z
Hello.
$cat < z
Hello.
$cat >> z
Hello World.
$cat < z
Hello.
Hello World.
$



Mark O. Stitson
Wed Sep 25 10:45:32 BST 1996