Sometimes you want everything in one file: the output and the errors, in one place.
2>&1 means: send stream 2 to the place where stream 1 goes now.
text
learner@tidepool:~$ cat prices.txt missing.txt > all.txt 2>&1
learner@tidepool:~$ cat all.txt
tea 4.50
coffee 3.20
cat: missing.txt: No such file or directoryThe order is important
The shell reads the redirects from left to right:
1. > all.txtstream 1 now goes to all.txt
2. 2>&1stream 2 goes where stream 1 goes: all.txt
The other order gives a different result:
| Line | Output | Errors |
|---|---|---|
cmd > all.txt 2>&1 | all.txt | all.txt |
cmd 2>&1 > all.txt | all.txt | The terminal |
In the second line, 2>&1 comes first. At that time, stream 1 still goes to the terminal. So stream 2 goes to the terminal too.
A shorter form
Bash also has &>, which sends both streams to one file:
text
learner@tidepool:~$ cat prices.txt missing.txt &> all.txtYou will see both forms. > file 2>&1 also works in other shells.