Redirection
Point stdin, stdout and stderr at files with <, >, >>, 2> and 2>&1. Covers why order matters, how sort file > file destroys data, noclobber, and /dev/null.
Redirection
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- > FILE sends stdout to a file, truncating it first. >> FILE appends. < FILE feeds a file to stdin. 2> FILE sends stderr.
- The shell opens and truncates the output file before the command starts, so sort f > f leaves f empty.
- 2>&1 means make channel 2 point where channel 1 points right now. Redirections are processed left to right, so cmd > file 2>&1 and cmd 2>&1 > file differ.
- /dev/null discards anything written to it and reads as empty. It is how you silence one stream: cmd 2>/dev/null.
- set -o noclobber makes > refuse to overwrite an existing file, and >| forces it. A redirect to a missing directory fails before the command runs.
Streams you can aim
The last lesson showed that every process starts with stdin, stdout and stderr, wired to the terminal by whoever launched it. The shell is the one that launches your commands, so it can wire them to something else first. That wiring step is redirection. The program never knows. It still writes to channel 1; the shell has quietly pointed channel 1 at a file.
I ran the following in a scratch directory with the web-log fixture, using Bash 5.3 on macOS.
Output to a file: > and >>
$ echo first > out.txt; echo second > out.txt; cat out.txt
second
$ echo third >> out.txt; cat out.txt
second
third
> creates the file or empties it if it exists. >> adds to the end. A redirection creates the file even when the command prints nothing: true > empty.out left a zero-byte empty.out.
Input from a file: <
$ wc -l < data/people.csv
6
$ sort < data/people.csv | head -2
ada,infra,london,91
grace,compilers,new york,95
wc -l < file and wc -l file give the same count, with one difference: given a file name, wc prints the name too. With <, it only sees a stream and cannot know where it came from. (BSD wc pads the number with spaces, as seen above; GNU wc doesn’t.)
Errors: 2> and 2>&1
Put the channel number in front of the >:
$ ls real.txt missing.txt > good.txt 2> bad.txt
$ cat good.txt
real.txt
$ cat bad.txt
ls: missing.txt: No such file or directory
To merge errors into the same place as output, write 2>&1. Read it as “channel 2 goes where channel 1 goes right now”. The word now is the whole trick, because the shell handles redirections strictly left to right:
$ ls real.txt missing.txt > both.txt 2>&1; cat both.txt
ls: missing.txt: No such file or directory
real.txt
$ ls real.txt missing.txt 2>&1 > only-out.txt
ls: missing.txt: No such file or directory
$ cat only-out.txt
real.txt
In the first command, stdout went to the file, then stderr was pointed at the file as well. In the second, stderr was copied from stdout while stdout was still the terminal, and only then did stdout move to the file. The error stayed on screen. Bash also has &> as shorthand for the first form and |& for sending both into a pipe; I ran both and they behaved as the long forms. They are Bash features, so don’t use them in scripts that must run under plain sh.
The classic accident
The shell sets up redirections before starting the command, and > truncates immediately. So this destroys your data:
$ printf 'b\na\n' > s.txt
$ sort s.txt > s.txt; echo "size=$(wc -c < s.txt)"
size= 0
sort hadn’t read a byte when the file was emptied. cat s.txt > s.txt did the same in my run. Two safe patterns: write to a temporary file and rename it (sort s.txt > s.tmp && mv s.tmp s.txt), or use a tool’s own in-place flag (sort -o s.txt s.txt). I ran both and got a then b each time.
If you want a seatbelt, set -o noclobber makes > refuse to overwrite an existing file. >| forces it, and >> is still allowed:
$ set -o noclobber; echo new > k.txt
bash: k.txt: cannot overwrite existing file
$ echo forced >| k.txt; cat k.txt
forced
/dev/null and friends
/dev/null is a special file that swallows what you write and reads as empty. It’s the standard way to silence a stream:
$ ls real.txt missing.txt 2>/dev/null
real.txt
$ cat /dev/null | wc -c
0
Silence stderr and the exit status is still 1, as the previous lesson showed. Other forms you will meet: a here-string, wc -w <<< "one two three" (printed 3); a here-document with <<, which a later lesson covers; and tee, which writes to a file and passes the data along, so echo hello | tee tee.txt printed hello and saved it.
You can also redirect a group: { echo a; echo b; } > grp.txt captured both lines, and (cd data; ls) > listing.txt listed data’s contents without changing your directory.
Small surprises
- The redirect is part of the command line, not the command, so it can come first:
> early.txt echo hiworked. - If the command isn’t found, the shell still created the output file (
nf.txt, zero bytes), and the “command not found” message went to the redirected stderr file. echo x > nodir/filefailed with “No such file or directory” and the command never ran.- An unquoted empty variable gave
bash: $NOPE: ambiguous redirect. Quote filenames from variables. - File descriptors above 2 are usable:
exec 3> fd3.txt; echo "via fd3" >&3; exec 3>&-wrote to a file through channel 3 and then closed it.
About the video
Microsoft Developer’s “How to Use Redirection and Pipelines in Bash [11 of 20]” was published 15 February 2023 and runs 9 minutes 50 seconds. Its description lists “How to use redirection” from 0:00 and “How to use pipelines” from 7:10. I clipped 0:00 to 7:10, so the pipelines half is left for the next lesson. English per its title and description. I couldn’t read a transcript, so I haven’t checked whether it covers 2>&1, the truncation accident or /dev/null, and I’d expect it not to cover all of them. Those are my additions. You Suck at Programming’s 3-minute video on the same topic is listed as a second view.
What I did not run
Linux, redirection in Zsh, and exec redirection that persists across an interactive session.
Next
Redirection connects a stream to a file. A pipe connects one command’s stdout directly to the next command’s stdin: pipes and pipelines.
Check yourself
You run sort data.txt > data.txt to sort a file in place. What do you end up with?
An empty file. The shell truncates data.txt when it sets up the redirect, before sort reads anything. Use sort -o data.txt data.txt, or write to a temp file and mv it back.
What is the difference between cmd > out 2>&1 and cmd 2>&1 > out?
The first sends both streams to the file. The second points stderr at where stdout currently goes (the terminal) and only then sends stdout to the file, so errors still appear on screen.
How do you run a command silently but still see its errors?
Send stdout to /dev/null: cmd > /dev/null. Errors on stderr still reach the terminal.
What does >> do that > does not?
It appends to the file instead of truncating it. Both create the file if it does not exist.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.