Combining Standard Output and Standard Error
Sometimes you want the results of a command and its error messages in the same place: one log file that tells the whole story, one pipeline that processes everything, or one variable that holds all the text. Bash gives you several ways to merge standard output and standard error. The classic form is 2>&1, and Bash adds the shorter &> and |&.
The examples use a folder with one file, real.txt, and one name that does not exist, missing.txt:
echo 'one' > real.txt
Duplicating a Descriptor with 2>&1
The operator 2>&1 means "make file descriptor 2 point to the same place that file descriptor 1 points to right now". The & in front of the 1 tells Bash that the number is a descriptor, not a file called 1.
To send both streams into one file, combine > and 2>&1:
ls real.txt missing.txt > all.txt 2>&1
cat all.txt
Output:
ls: cannot access 'missing.txt': No such file or directory
real.txt
The screen showed nothing when the first command ran. Both the listing and the error message went into all.txt.
Why the Order Matters
Bash processes redirections from left to right, and each one takes effect immediately. That is why > all.txt 2>&1 works, and the reverse order does not:
ls real.txt missing.txt 2>&1 > partial.txt
cat partial.txt
Output:
ls: cannot access 'missing.txt': No such file or directory
real.txt
The first line of the output came from the first command, on the screen, and partial.txt holds only real.txt. Follow the steps for each form to see why.
For > file 2>&1:
> filepoints descriptor 1 at the file.2>&1points descriptor 2 at wherever descriptor 1 points now, which is the file.- Both streams go to the file.
For 2>&1 > file:
2>&1points descriptor 2 at wherever descriptor 1 points now, which is the terminal.> filethen moves descriptor 1 to the file.- Standard output goes to the file, and standard error stays on the terminal.
The mental model is that 2>&1 copies the current destination of descriptor 1, and does not link the two descriptors permanently. A later change to descriptor 1 does not affect the copy.
The second form is not useless. It is the key to a trick shown later in this lesson: sending only the errors through a pipe.
The Bash Shortcut &>
Bash provides a shorter way to send both streams to a file. The operator &> redirects standard output and standard error together:
ls real.txt missing.txt &> all2.txt
cat all2.txt
Output:
ls: cannot access 'missing.txt': No such file or directory
real.txt
The file holds the same two lines as before. To append instead of overwrite, use &>>:
ls real.txt missing.txt &>> all2.txt
wc -l < all2.txt
Output:
4
Bash also accepts >& file, which means the same as &> file. Most people prefer &> because it reads more clearly, and the Bash manual names it as the preferred form. Both are shortcuts for > file 2>&1.
A Portability Warning
The operators &> and &>> are Bash features. Other shells do not always treat them the same way. In Dash, which is what sh points to on Debian and Ubuntu, &> is not a combined redirection. It is read as & (run in the background) followed by >:
ls missing.txt &> d.txt
echo "after"
Run with dash instead of bash, the first line started ls missing.txt in the background and created an empty d.txt afterward. The error message was shown on the screen, and the file stayed empty:
after
ls: cannot access 'missing.txt': No such file or directory
The order of those two lines can vary, because the background command runs at the same time as echo. For scripts that must run under sh and not only under Bash, write > file 2>&1 instead. It works everywhere.
Appending Both Streams
For a log file that collects everything over many runs, append the standard output and point the standard error to the same place:
echo "run 1" >> run.log
ls missing.txt >> run.log 2>&1
cat run.log
Output:
run 1
ls: cannot access 'missing.txt': No such file or directory
In Bash, ls missing.txt &>> run.log does the same thing in a shorter form.
Sending Both Streams Through a Pipe
A pipe carries only standard output. To pass both streams to the next command, merge them first with 2>&1:
ls real.txt missing.txt 2>&1 | sed 's/^/> /'
Output:
> ls: cannot access 'missing.txt': No such file or directory
> real.txt
The sed command added > to the start of each line, and it processed the error message too. Bash has a shorter form, |&, which means 2>&1 |:
ls real.txt missing.txt |& sed 's/^/| /'
Output:
| ls: cannot access 'missing.txt': No such file or directory
| real.txt
Like &>, the |& operator is specific to Bash and some other modern shells. Use 2>&1 | when portability matters.
Saving and Showing Output with tee
The tee command copies standard input to a file and also passes it on to standard output. Combined with 2>&1, it records everything and shows it at once:
ls real.txt missing.txt 2>&1 | tee both.txt | wc -l
cat both.txt
Output:
2
ls: cannot access 'missing.txt': No such file or directory
real.txt
The count 2 came from wc -l at the end of the pipeline. The file both.txt holds both lines. A later lesson explains tee in detail.
Sending Only the Errors Through a Pipe
Because 2>&1 > /dev/null puts descriptor 2 where descriptor 1 pointed first, which is the pipe, and then sends descriptor 1 to the null device, it passes only the errors on:
ls missing.txt 2>&1 > /dev/null | sed 's/^/err-only: /'
Output:
err-only: ls: cannot access 'missing.txt': No such file or directory
Counting the lines of each form shows the difference:
ls real.txt missing.txt 2>&1 >/dev/null | wc -l
ls real.txt missing.txt >/dev/null 2>&1 | wc -l
Output:
1
0
The first pipeline counted the one error line. In the second, everything was discarded before the pipe, so there was nothing to count. This shows again that the order of > and 2>&1 changes the result.
Discarding Everything
To silence a command completely, send both streams to /dev/null:
ls real.txt missing.txt > /dev/null 2>&1
echo "status: $?"
Output:
status: 2
Nothing was printed, and the exit status 2 is still available. The Bash shortcut ls real.txt missing.txt &> /dev/null behaves the same way. Scripts use this form when they only care about the status, for example to test whether a command exists without any output.
Capturing Both Streams in a Variable
Command substitution captures only standard output by default. To store the error text as well, merge the streams inside the substitution:
out=$(ls real.txt missing.txt 2>&1)
echo "$out"
Output:
ls: cannot access 'missing.txt': No such file or directory
real.txt
Without the 2>&1, the error message would have appeared on the screen when the command ran and would not be in $out.
Redirecting a Group of Commands
To merge the streams of several commands, put the redirections after the group:
{ echo "out"; ls missing.txt; } > grp.txt 2>&1
cat grp.txt
Output:
out
ls: cannot access 'missing.txt': No such file or directory
The same pattern works after a loop's done or after a function call.
Redirecting for a Whole Script
A script can send all of its own output, normal and error, to a log by using exec with redirections at the top. The exec command, when it has no command to run, applies the redirections to the shell itself for the rest of the script:
exec > exe.log 2>&1
echo "this is stdout"
ls missing.txt
echo "done"
When this script runs, nothing appears on the screen. The log file receives:
this is stdout
ls: cannot access 'missing.txt': No such file or directory
done
The pattern is useful for scheduled scripts that run without anyone watching, because everything the script prints ends up in one place. Remember that after the first line there is no output on the terminal at all, so a script that asks the user questions should not use it.
The Order of Lines in the Combined Output
When both streams go to the same file, the lines appear in the order the program wrote them. This script alternates between the two streams:
echo "1 out"
echo "2 err" >&2
echo "3 out"
echo "4 err" >&2
Run with bash mix.sh > mix.txt 2>&1, the file contains:
1 out
2 err
3 out
4 err
The lines kept their order because both descriptors share one open file. Larger programs may buffer their standard output and write it in chunks when it goes to a file, so the interleaving can differ for programs other than echo and the shell itself.
Swapping the Two Streams
With a temporary third descriptor, you can swap standard output and standard error, so that the normal output travels on the error channel and the other way around:
ls real.txt missing.txt 3>&1 1>&2 2>&3 3>&- | sed 's/^/stdout-now: /'
Output:
real.txt
stdout-now: ls: cannot access 'missing.txt': No such file or directory
Read the redirections from left to right:
3>&1saves the current standard output (the pipe) as descriptor 3.1>&2points standard output to the terminal, where standard error pointed.2>&3points standard error to the saved pipe.3>&-closes descriptor 3, because it is no longer needed.
The listing now reached the screen directly, and the error message went through the pipe, where sed marked it. You will rarely need this, but it shows that the numbered descriptors are real, independent connections that can be copied and moved.
Sending Standard Output to Standard Error
The reverse of 2>&1 is 1>&2 (or >&2), which makes standard output follow standard error. It is the standard way for a script to print a message on the error channel, as in echo "message" >&2. When you combine it with another redirection, the same left-to-right rule applies: echo "to stderr" 1>&2 2> /dev/null first points standard output at the terminal-connected error channel, then discards the error channel itself, so the message still shows on the screen.
Choosing the Right Form
| Goal | Portable form | Bash shortcut |
|---|---|---|
| Both streams to a file, replacing it | cmd > file 2>&1 | cmd &> file |
| Both streams appended to a file | cmd >> file 2>&1 | cmd &>> file |
| Both streams into a pipe | cmd 2>&1 | next | cmd |& next |
| Throw everything away | cmd > /dev/null 2>&1 | cmd &> /dev/null |
| Only errors into a pipe | cmd 2>&1 > /dev/null | next | none |
Use the portable forms in scripts that start with #!/bin/sh, and use either style in scripts that start with #!/usr/bin/env bash. Whichever you choose, keep the same form throughout a script so readers do not have to translate between them.