Redirects — Sending Output Somewhere Else
By default, everything a command prints lands on your screen and then scrolls away. Asha wants to save the list of her garden files, add a line to a log every week, and keep error messages out of her reports. Redirects let her choose where a command's output goes, without changing the command.
The rule
>replaces,>>appends,2>catches errors.
Every command has one input and two separate outputs. There's the normal output and there's a separate channel for error messages (the Text Processing section explains these channels in detail). Redirects are symbols that re-route them:
| Redirect | Meaning |
|---|---|
> file |
send normal output to a file, replacing its contents |
>> file |
send normal output to a file, adding to the end |
2> file |
send error messages to a file |
2>&1 |
send errors to wherever normal output is going right now |
&> file |
Bash shorthand: both outputs to one file |
< file |
read input from a file instead of the keyboard |
$ cd ~/garden
$ ls > files.txt # fresh list, old contents gone
$ echo "week 23: watered" >> log.txt # add one line at the end
$ ls plots missing-dir 2> errors.txt # listing on screen, error in file
$ sort < harvest.csv # sort reads the file as inputThe file /dev/null throws away anything written to it. It's handy for silencing messages you don't need:
$ find / -name harvest.csv 2> /dev/null # hide all the "Permission denied" linesThe shell sets up redirects before the command runs. That's why > empties the file at once, even if the command then fails.