Skip to the workspace
Pebellslearn by building
Shell and Other Basics  ›  Lesson

Redirects — Sending Output Somewhere Else

Redirects 15 min> replaces a file with a command's output, >> appends to it, 2> captures error messages, and 2>&1 sends errors to wherever normal output is going.

linux / Redirects — Sending Output Somewhere Else

Explore each scene at your own pace.

01 · The rule

The rule

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 input

The 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" lines

The shell sets up redirects before the command runs. That's why > empties the file at once, even if the command then fails.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.