[Next] [Previous] [Up] [Top] [Contents]

6.2 File Redirection

6.2.2 Sh

2> file direct stderr to file

> file 2>&1 direct both stdout and stderr to file

>> file 2>&1 append both stdout and stderr to file

2>&1 | command pipe stdout and stderr to command

To redirect stdout and stderr to two separate files you can do:

$ command 1> out_file 2> err_file

or, since the redirection defaults to stdout:

$ command > out_file 2> err_file

With the Bourne shell you can specify other file descriptors (3 through 9) and redirect output through them. This is done with the form:

n>&m redirect file descriptor n to file descriptor m

We used the above to send stderr (2) to the same place as stdout (1), 2>&1, when we wanted to have error messages and normal messages to go to file instead of the terminal. If we wanted only the error messages to go to the file we could do this by using a place holder file descriptor, 3. We'll first redirect 3 to 2, then redirect 2 to 1, and finally, we'll redirect 1 to 3:

$ (command 3>&2 2>&1 1>&3) > file

This sends stderr to 3 then to 1, and stdout to 3, which is redirected to 2. So, in effect, we've reversed file descriptors 1 and 2 from their normal meaning. We might use this in the following example:

$ (cat file 3>&2 2>&1 1>&3) > errfile

So if file is read the information is discarded from the command output, but if file can't be read the error message is put in errfile for your later use.

You can close file descriptors when you're done with them:

m<&- closes an input file descriptor

<&- closes stdin

m>&- closes an output file descriptor

>&- closes stdout

Introduction to Unix - 14 AUG 1996
[Next] [Previous] [Up] [Top] [Contents]