UNIX Primer

Home | Primer Home


Redirection

When we run a program, sometimes we wish to do something else with the output sent back to us other rather than send it straight to the monitor. To do this, we use what is called 'redirection'. Before getting into detail about redirection, we need to understand that output in UNIX is handled by sending data to special 'files' which are always open. These two output files are often referred to as 'standard output' (stdout for short) and 'standard error' (stderr for short). Data sent to these two files is normally transmitted to your screen.

Simple redirection sends the data from standard output to a file. The syntax for simple redirection is as follows:

command > filename
command >> filename


The first version will create the file specified if it doesn't exist and replace it if it does. The latter will also create the file if it doesn't exist, but it will append the data to the bottom if the file if it already exists. Try using this syntax with a simple command like 'ls'. For instance, try typing 'ls > out.txt' and then look at the contents of 'out.txt'.

Note that error messages (messages sent to standard error) are not included in that type of redirection. We can fix this by changing where 'standard error' is sent. For instance, we can do the following to redirect standard error to standard output:

command 2>&1
command 2>&1 > filename


The meaning of the first statement is that UNIX should redirect standard error (whose file descriptor is '2') to the address of standard output (whose file descriptor is '1'). The second one then redirects standard output (to which both files' output is now being sent) to a filename.

As you might have guessed, we can also redirect from a file into a program. If the program expects to read from standard input (usually associated with the keyboard), we can directly provide input by using this form of redirection.

command < inputfile

This sends the contents of inputfile line by line into the program through standard input (as if it were typed on the keyboard).

For more information, consult the 'man' page for your shell and search for 'redirection'.



Designed by D. Kaminsky
Edited by Diana Palsetia
© University of Pennsylvania, 2008