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.
The shortcut
Read a redirect by its number and arrow. With no number, > means output 1, normal output. 2 means the error stream. One arrow replaces and two arrows append. Then read 2>&1 as "make 2 go where 1 is going at this moment", and remember the shell reads redirects left to right.
The goal
Both the report and any errors from
./harvest-reportshould go intoreport.log.
The most painful trap is sort harvest.csv > harvest.csv. The shell empties harvest.csv before sort gets to read it, so the data is lost. Write to a new file, then rename it.
Drills
Answer fast — trust the rule.
log.txt has 10 lines. Asha runs echo done > log.txt. How many lines does it have now?
Which command adds a line to the end of log.txt without losing what's there?
How do you hide only the error messages from a command?
Which line puts BOTH normal output and errors into out.txt?
What happens with sort harvest.csv > harvest.csv?
Remember
>replaces,>>appends,2>catches errors, and<feeds a file in as input.- Read the number and the arrows.
2>&1means "errors go where output is going right now", so put it after> file. - Never redirect output into the same file the command is reading.
