C.W.K.
Stream
Lesson 02 of 10 · published

Output Redirection: > and >>

~10 min · redirect, stdout, append

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

Save what would have hit the screen

cmd > file sends stdout to file, replacing whatever was there. cmd >> file appends to it. The screen stays empty unless the program also writes to stderr.

Truncate vs append

  • > — overwrite. The file is truncated to zero before the command runs.
  • >> — append. Existing content stays.

The truncation happens early: cmd > file blanks file even if cmd immediately fails. If you want fresh-write-or-fail, use >| with set -o noclobber (see callout below).

Stdin redirection from a file

cmd < file sends file contents to cmd's stdin. wc -l < lines.txt counts lines without spawning cat. sort < data.txt, tr a-z A-Z < input.txt are the canonical patterns.

Combining redirections

You can stack them: cmd < in.txt > out.txt 2> err.txt. Order doesn't matter for separate fds, but it matters for the same fd: cmd > out.txt 2>&1 sends stderr to wherever stdout currently goes (= out.txt). cmd 2>&1 > out.txt redirects stderr to the original stdout (still terminal!) and only then redirects stdout. Different result.

Code

Append vs overwrite·bash
echo 'first'  > log.txt
echo 'second' > log.txt          # overwrites
echo 'third'  >> log.txt         # appends
cat log.txt                      # second\nthird
Capture both stdout and stderr to one file·bash
# Bash / zsh — order matters
make all > build.log 2>&1
# Bash 4+ shorthand
make all &> build.log
# Append both
make all >> build.log 2>&1

External links

Exercise

Run echo 'first' > log.txt, echo 'second' > log.txt, then echo 'third' >> log.txt and cat log.txt. Confirm only second and third remain. Then try set -o noclobber; echo nope > log.txt and watch it refuse.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.