Back to tools

Redirections and pipes, drawn

Every command has 3 "doors": 0 standard input, 1 standard output, 2 standard error. Redirections and pipes change where they point. Type a command line to see where they end up, how they got there step by step, and what running it does.

Where they end up

The arrows are pipes: the left command’s output feeds the right command’s input.

"2>&1" comes before "> all.txt": standard output still pointed to the screen (terminal) then, so the errors went there, not into all.txt. For both in the file, write > all.txt 2>&1

ls notes.txt nofile
  • 0 standard inputthe keyboard (terminal)
  • 1 standard outputthe file all.txt (written)
  • 2 standard errorthe screen (terminal)
Step by step

ls notes.txt nofile

  1. At the start (pipes connected first):0→the keyboard (terminal)1→the screen (terminal)2→the screen (terminal)
  2. 2>&1standard error (fd 2) copies where fd 1 points right now: the screen (terminal). A copy, not a link: changing fd 1 later does not move fd 20→the keyboard (terminal)1→the screen (terminal)2→the screen (terminal)
  3. > all.txtstandard output (fd 1) now points to all.txt: created if missing, emptied first if it exists0→the keyboard (terminal)1→the file all.txt (written)2→the screen (terminal)
Explain
What actually happens

Run in the simulator in /home/user/demo; checked against real bash.

On the screen

ls: cannot access 'nofile': No such file or directory

■ standard output ■ standard error · exit status 2

Files in the directory

  • all.txtnew

    notes.txt
    
  • log.txtunchanged

  • names.txtunchanged

  • notes.txtunchanged

The sample directory
  • notes.txt
    notes
  • names.txt
    bob
    alice
    carol
  • log.txt
    earlier line

nofile does not exist, so ls notes.txt nofile prints one normal line and one error.

Good to know
  • 0 is standard input (the keyboard by default), 1 standard output (the screen), 2 standard error (the screen too).
  • > overwrites, >> appends; > empties the file before the command runs, so do not read and write one file (sort f > f gives an empty file).
  • Redirections are done left to right: > file 2>&1 puts both outputs in the file; 2>&1 > file only standard output.
  • 2>&1 means "point 2 where 1 points right now": a copy, not a link that follows 1 later.
  • A pipe carries standard output only; for errors too use 2>&1 | or |&.
  • /dev/null is a black hole: > /dev/null throws output away, 2> /dev/null the errors.
  • To see the output and save it, use tee: cmd | tee out.txt (tee -a appends).
  • &> file is bash’s shorthand for > file 2>&1; plain sh may not have it.
  • Every stage of a pipe runs in a subshell: variables set in cmd | while read … are gone after the loop; use while read …; done < file instead.
  • A pipeline’s exit status is its last command’s; in scripts add set -o pipefail, or look at ${PIPESTATUS[@]}.

Try these

Basics
Merging
Pipes
Pipe exit status
Traps