Sending Both Output and Error Messages to the Same File

Problem

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?

Solution

Use the shell syntax to redirect standard error messages to the same place as standard output.

Preferred:

$ both >& outfile

or:

$ both &> outfile

or older and slightly more verbose:

$ both > outfile 2>&1

where both is just our (imaginary) program that is going to generate output to both STDERR and STDOUT.

Discussion

&> 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 error (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 read-able, and redirect standard output to the same place to which you ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.