Using redirection, you can redirect output or error messages to separate files, but how do you capture all the output and error messages to a single file?
Use the shell syntax to redirect standard error messages to the same place as standard output.
Preferred:
1 |
$ both >& outfile |
or:
1 |
$ both &> outfile |
or older and slightly more verbose:
1 |
$ both > outfile 2>&1 |
where both is just our (imaginary) program that is going to generate output to both STDERR and STDOUT.
&> or >& is a shortcut that simply sends both STDOUT and STDERR to the same place—exactly what we want to do.
In the third example, the 1 appears to be used as the target of the redirection, but the >& says to interpret the 1 as a file descriptor instead of a filename.
In fact, the 2>& are a single entity, indicating that standard output (2) will be redirected (>) to a file descriptor (&) that follows (1).
The 2>& all have to appear together without spaces, otherwise the 2 would look just like another argument, and the & actually means something completely different when it appears by itself.
(It has to do with running the command in the background.)
It may help to think of all redirection operators as taking a leading number (e.g., 2>) but that the default number for > is 1, the standard output file descriptor.
You could also do the redirection in the other order, though it is slightly less readable, and redirect standard output to the same place to which you have already redirected standard error:
1 |
$ both 2> outfile 1>&2 |
The 1 is used to indicate standard output and the 2 for standard error.
By our reasoning (above) we could have written just >&2 for that last redirection, since 1 is the default for >, but we find it more readable to write the number explicitly when redirecting file descriptors.
Note the order of the contents of the output file. Sometimes the error messages may appear sooner in the file than they do on the screen.
That has to do with the unbuffered nature of standard error, and the effect becomes more pronounced when writing
to a file instead of the screen.