Redirection, Pipes and File Descriptors

Redirection, Pipes and File Descriptors in Bash: --- An outside broadcast truck parked behind a stadium has a steel panel at the back called a patch bay: a…


The Analogy: The Outside Broadcast Truck's Patch Bay

An outside broadcast truck parked behind a stadium has a steel panel at the back called a patch bay: a grid of numbered jack sockets, each one a signal path. Socket 1 is the main programme feed. Socket 2 is the talkback line the director shouts down. Socket 0 is the incoming feed from the stadium's own camera. Nothing in that truck knows or cares where a signal ends up -- the commentary microphone is wired to socket 1 and stops thinking about it. Whether socket 1 goes to a tape machine, a satellite uplink, or a dead patch that discards everything is decided at the panel, by an engineer with a handful of cables, minutes before transmission.

The engineer works from a written patch sheet, down it in order, one line at a time. Line one might read "socket 1 to tape machine A". Line two might read "socket 2 to wherever socket 1 currently goes", and that second instruction is copied from the panel as it stands at that moment, not as it will stand later. A patch is not a promise about the future; it is a cable plugged into whatever the destination happens to be when the plug goes in. Re-patch socket 1 afterwards and the cable from socket 2 stays where it was put, still feeding tape machine A, now disconnected from the programme feed it was supposed to shadow.

There is also a short link cable in the kit bag with a paper tag reading "follow 1". Its job is to take socket 2 and hang it off whatever socket 1 is currently patched to, so the director's talkback lands on the same tape as the commentary. It is the most used cable in the truck and the most misunderstood, because the tag lies slightly: it does not mean "follow socket 1 around", it means "go where socket 1 is pointing right now". The tag should read "copy 1 as it stands", but nobody has ever reprinted it.

The failure mode is quiet and expensive. An engineer in a hurry plugs the "follow 1" link in first, while socket 1 is still pointing at the gallery monitors, and only then patches socket 1 across to tape machine A. Everything on the panel looks correct. The gallery meters dance, the commentary is audible in headphones, the talkback is audible in headphones, and the tape machine's meter shows signal because the commentary really is arriving. Nothing reports a fault. It is only at playback the next morning, when the producer wants the director's cue for the second goal, that anybody discovers the talkback never reached the tape -- it went to a monitor switched off two hours before kickoff. The order of two cables, invisible in every check anyone thought to run, destroyed half the recording.


Syntax or Core Structure

A bash process inherits three open descriptors: 0 is standard input, 1 is standard output, 2 is standard error. A redirection operator re-patches one of them for the duration of a single command. Here is a program that deliberately writes to both output streams and then fails, so every redirection below has something visible to move around.

#!/usr/bin/env bash
printf 'compiling parts.c\n'
printf 'warning: unused variable rpm\n' >&2
printf 'compiling gears.c\n'
printf 'error: gears.c line 44: missing bracket\n' >&2
exit 3

Two lines go to descriptor 1 and two to descriptor 2. On a terminal both are patched to the same screen, so all four appear and the split is invisible. Redirection makes it visible. This driver runs the program five times with five different patches on the panel.

#!/usr/bin/env bash
printf '%s\n' '-- both streams to the terminal'
./noisy.sh; printf 'exit status %d\n' "$?"
printf '%s\n' '-- stdout to out.txt, stderr left alone'
./noisy.sh > out.txt; printf 'exit status %d\n' "$?"
printf '%s\n' '-- each stream to its own file'
./noisy.sh > out.txt 2> err.txt
printf 'out.txt has %d lines, err.txt has %d lines\n' "$(wc -l < out.txt)" "$(wc -l < err.txt)"
printf '%s\n' '-- both into one file, correct order'
./noisy.sh > both.txt 2>&1
printf 'both.txt has %d lines\n' "$(wc -l < both.txt)"
printf '%s\n' '-- both into one file, wrong order'
./noisy.sh 2>&1 > wrong.txt
printf 'wrong.txt has %d lines\n' "$(wc -l < wrong.txt)"

Output:

-- both streams to the terminal
compiling parts.c
warning: unused variable rpm
compiling gears.c
error: gears.c line 44: missing bracket
exit status 3
-- stdout to out.txt, stderr left alone
warning: unused variable rpm
error: gears.c line 44: missing bracket
exit status 3
-- each stream to its own file
out.txt has 2 lines, err.txt has 2 lines
-- both into one file, correct order
both.txt has 4 lines
-- both into one file, wrong order
warning: unused variable rpm
error: gears.c line 44: missing bracket
wrong.txt has 2 lines

Read the last two blocks together, because they are the whole lesson in six characters. > both.txt 2>&1 captured four lines; 2>&1 > wrong.txt captured two and let the other two escape to the terminal. The operators are identical and only their order differs. That is the "follow 1" link plugged in before the destination cable -- and note what did not happen: no error, no warning, no non-zero status. The second command reported exit status 3 just like the first, wrote a file just like the first, and quietly threw away half of what it was asked to keep.

Redirection and exit status are independent: the third block applies both > and 2>, both succeed, and the program still exits 3. A redirection failing is different -- if bash cannot open the file it never runs the command, and the status is the shell's, not the program's.


Technical Depth: The Patch Sheet, Read In Order

The three descriptors you are given

Every process bash starts inherits three open descriptors from the shell, and they are inherited, not created -- which is why a program has no say in where its own output lands.

DescriptorNameDefault patchWhat writes or reads it
0standard inputthe terminal keyboardread, cat with no file, anything awaiting input
1standard outputthe terminal screenprintf, echo, a program's results
2standard errorthe terminal screendiagnostics, warnings, bash's error messages

Descriptors 1 and 2 share a default, and that is why the distinction gets forgotten until the day something is piped. Bash itself obeys the convention: results go to 1, anything a human needs to read but a program should not consume goes to 2. When bash prints command not found or unbound variable it writes to descriptor 2, so those messages survive > file and vanish under 2> file.

Redirection operators

OperatorEffectNote
> filepatch descriptor 1 to file, truncating itcreates the file if absent
>> filepatch descriptor 1 to file, appendingnever truncates
2> filepatch descriptor 2 to filethe digit binds to the operator with no space
n> filepatch descriptor n to filen may be 0 through 9
&> filepatch 1 and 2 to filebash-specific shorthand, order-proof
&>> filepatch 1 and 2 to file, appendingbash-specific shorthand
2>&1patch 2 to wherever 1 points nowthe "follow 1" link cable
1>&2patch 1 to wherever 2 points nowhow a function sends results to the log
< filepatch descriptor 0 to read filefails if the file is unreadable
<<< wordpatch 0 to a single line holding worda here-string
n>&-close descriptor nthe child sees it closed, not empty
> followed by a barpatch 1 to a file even under noclobberdeliberate override

The digit is part of the operator, not a separate word. 2> err.txt redirects descriptor 2; 2 > err.txt passes the string 2 as an argument and redirects descriptor 1.

Order is left to right, and 2>&1 is a copy

Bash applies redirections in the order written, and 2>&1 means "make descriptor 2 a duplicate of descriptor 1 as it stands at this instant". Trace the two forms from the driver above:

  • > both.txt 2>&1 -- descriptor 1 is patched to both.txt; then descriptor 2 is made a copy of descriptor 1, so it points there too. Four lines land in the file.
  • 2>&1 > wrong.txt -- descriptor 2 is made a copy of descriptor 1, which still points at the terminal; then descriptor 1 moves to wrong.txt. Descriptor 2 keeps its old destination. Two lines in the file, two on the terminal.

The dependency is one-way and one-time. Nothing re-patches descriptor 2 when descriptor 1 moves, because the duplicate holds a destination, not a reference. If you want both streams in one file and do not want to think about order, &> file cannot be got wrong -- but it is a bashism, so scripts that must run under a POSIX sh use the ordered form.

Numbered descriptors and exec

Descriptors 3 through 9 are yours, and exec with redirections but no command patches the panel for the rest of the script rather than for one command. That gives a script a private output channel, unaffected by anything it does to descriptors 1 and 2.

#!/usr/bin/env bash
exec 3> report.txt
printf 'report line one\n' >&3
printf 'this goes to the terminal\n'
printf 'report line two\n' >&3
exec 3>&-
printf 'report.txt now holds %d lines:\n' "$(wc -l < report.txt)"
cat report.txt
exec 4< report.txt
IFS= read -r first <&4
exec 4<&-
printf 'first line read back through fd 4: %s\n' "$first"

Output:

this goes to the terminal
report.txt now holds 2 lines:
report line one
report line two
first line read back through fd 4: report line one

exec 3> report.txt opens and truncates the file once. Every later >&3 writes through the descriptor that is already open, so nothing truncates it again -- precisely the difference from writing > report.txt twice. exec 3>&- closes it. On the read side exec 4< report.txt keeps a read position, so successive read -r <&4 calls walk down the file, unlike read -r < report.txt which reopens at line one every time.

Applied to descriptor 1 with no number, the same trick redirects the whole script onward. A script beginning exec > run.log 2>&1 prints nothing to the terminal: both streams are in the log from that point, and the pair obeys the same left-to-right rule, so it must be written in that order.

A pipe is two processes, one of them a subshell

a | b patches descriptor 1 of a to descriptor 0 of b through an in-memory buffer. Both sides run at once, and by default bash runs every stage in a subshell -- so the last stage's variables do not survive.

#!/usr/bin/env bash
printf '%s\n' '-- counting in a pipeline'
n=0
printf 'a\nb\nc\n' | while IFS= read -r _; do n=$((n + 1)); done
printf 'after the pipeline, n=%d\n' "$n"
printf '%s\n' '-- the same loop fed by redirection'
n=0
while IFS= read -r _; do n=$((n + 1)); done < <(printf 'a\nb\nc\n')
printf 'after process substitution, n=%d\n' "$n"
printf '%s\n' '-- and with lastpipe'
shopt -s lastpipe
n=0
printf 'a\nb\nc\n' | while IFS= read -r _; do n=$((n + 1)); done
printf 'with lastpipe, n=%d\n' "$n"

Output:

-- counting in a pipeline
after the pipeline, n=0
-- the same loop fed by redirection
after process substitution, n=3
-- and with lastpipe
with lastpipe, n=3

The first loop genuinely counted to three -- in a subshell that then exited, taking n with it. The read variable is named _ because it is deliberately unused. < <(...) is process substitution: bash runs the command in the background on a temporary descriptor and gives the loop a plain redirection, so the loop stays in the current shell and keeps its variable. shopt -s lastpipe instead runs the final stage in the current shell, but only takes effect when job control is off -- true in a script, false at an interactive prompt.

Keeping a copy: tee

A pipe delivers to exactly one reader. tee is the T-piece: it writes its input to a file and passes it on unchanged.

./noisy.sh 2>&1 | tee tee.log | grep -c .
printf 'tee.log kept %d lines\n' "$(wc -l < tee.log)"

Output:

4
tee.log kept 4 lines

The 2>&1 here is applied before the pipe, so both streams enter it: grep -c . counted four lines and tee.log holds the same four. Two things matter. The pipeline's exit status is grep's, so the 3 that noisy.sh exited with has been thrown away -- ${PIPESTATUS[0]} still holds it, and set -o pipefail makes the pipeline report the last stage that exited non-zero instead of simply the last stage. And merging the streams before tee is what makes the log complete, at the cost of no longer knowing which line came from which stream.

/dev/null and noclobber

/dev/null is the dead patch: writes are discarded, reads return end of file at once. 2>/dev/null silences diagnostics, >/dev/null discards results, and command >/dev/null 2>&1 runs something purely for its exit status. Discarding descriptor 2 hides bash's own messages about unbound variables and unreadable files just as effectively, so scope it narrowly.

Against the opposite hazard, set -C (set -o noclobber) makes > refuse to truncate a file that already exists.

#!/usr/bin/env bash
rm -f guard.txt
set -C
printf 'first write\n' > guard.txt
if ( printf 'second write\n' > guard.txt ) 2>/dev/null; then
  printf 'noclobber did not stop the overwrite\n'
else
  printf 'noclobber refused the overwrite, status %d\n' "$?"
fi
printf 'guard.txt still holds: %s\n' "$(cat guard.txt)"
printf 'forced write\n' >| guard.txt
printf 'after >| it holds  : %s\n' "$(cat guard.txt)"

Output:

noclobber refused the overwrite, status 1
guard.txt still holds: first write
after >| it holds  : forced write

The failing redirection is wrapped in a subshell because bash reports that error itself, from the shell rather than the command, so 2>/dev/null on the bare printf would not catch it; the subshell gives the message a stream that can be discarded and hands back a status of 1. >> is unaffected by noclobber because appending destroys nothing.


Real World Example: A Build Wrapper That Keeps The Streams Apart

A build wrapper is the natural home for everything above. It runs several tools that each write results to one stream and diagnostics to another, counts the diagnostics without letting them pollute the results, keeps a readable transcript, emits a machine-readable summary on its own channel, and reports an honest status. The step function below stands in for a compiler: it announces itself on descriptor 1, emits a requested number of warnings and errors on descriptor 2, and returns a requested status.

#!/usr/bin/env bash
set -u

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
cd "$work" || exit 1

step() {
  local name=$1 warns=$2 errs=$3 code=$4 i
  printf 'building %s\n' "$name"
  for ((i = 1; i <= warns; i++)); do printf '%s: warning: unused symbol w%d\n' "$name" "$i" >&2; done
  for ((i = 1; i <= errs;  i++)); do printf '%s: error: unresolved symbol e%d\n' "$name" "$i" >&2; done
  return "$code"
}

exec 3> summary.tsv
printf 'step\tstatus\tstdout\twarnings\terrors\n' >&3

total_w=0 total_e=0 failed=0
for spec in 'parts 1 0 0' 'gears 2 0 0' 'shafts 0 2 1' 'housing 1 0 0'; do
  set -- $spec
  name=$1 w=$2 e=$3 c=$4
  step "$name" "$w" "$e" "$c" > "$name.out" 2> "$name.err"
  status=$?
  outlines=$(wc -l < "$name.out")
  warns=$(grep -c ': warning: ' "$name.err" || true)
  errs=$(grep -c ': error: ' "$name.err" || true)
  printf '%s\t%d\t%d\t%d\t%d\n' "$name" "$status" "$outlines" "$warns" "$errs" >&3
  total_w=$((total_w + warns))
  total_e=$((total_e + errs))
  [ "$status" -eq 0 ] || failed=$((failed + 1))
  cat "$name.out" "$name.err" >> transcript.log
done
exec 3>&-

printf '%-8s %6s %7s %8s %6s\n' STEP STATUS STDOUT WARNINGS ERRORS
tail -n +2 summary.tsv | while IFS=$'\t' read -r s st o w e; do
  printf '%-8s %6d %7d %8d %6d\n' "$s" "$st" "$o" "$w" "$e"
done
printf '%-8s %6s %7s %8d %6d\n' 'totals' '' '' "$total_w" "$total_e"
printf 'steps failed: %d, transcript lines: %d\n' "$failed" "$(wc -l < transcript.log)"

Output:

STEP     STATUS  STDOUT WARNINGS ERRORS
parts         0       1        1      0
gears         0       1        2      0
shafts        1       1        0      2
housing       0       1        1      0
totals                         4      2
steps failed: 1, transcript lines: 10

Every number in that table is reconcilable by hand, which is the point of splitting the streams. Each step emitted one line on descriptor 1, so the STDOUT column is four ones. The warnings column reads 1, 2, 0, 1 and totals 4; the errors column reads 0, 0, 2, 0 and totals 2. Only shafts returned non-zero, so steps failed is 1. The transcript is both streams for all four steps -- four stdout lines plus six stderr lines -- and reports 10. Had the wrapper merged the streams with 2>&1 before counting, grep -c ': warning: ' would have scanned progress lines too, and any tool printing the word warning in its results would have inflated the count.

Two details are doing real work. set -- $spec is deliberately unquoted: it uses word splitting to turn one string into four positional parameters, safe only because these strings are literals in the script. And grep -c exits 1 when it matches nothing, which is a success for our purposes, so || true keeps the substitution from carrying a failure a later set -e would act on -- the captured value is still the 0 that grep printed.

The summary channel is the part worth copying. exec 3> summary.tsv opens the file once, and each iteration appends a row through >&3 without reopening or truncating. Descriptors 1 and 2 stay free for the per-step captures, so the rows never interleave with build output. The reporting loop reads the file back with IFS=$'\t' read -r, the tab-separated equivalent of the IFS= read -r habit, and tail -n +2 skips the header.

Now the genuine limits, and there is a real hole in what you just read. The summary file this wrapper exists to produce is written into $work, and $work is deleted by the EXIT trap, so the machine-readable artifact is destroyed on the way out and nothing downstream can consume it -- the program's advertised output cannot leave the program. That is the feature failing silently, and it survives testing because the table on the terminal looks complete. The second flaw is subtler and equally real: cat "$name.out" "$name.err" writes all of a step's stdout followed by all of its stderr, so the transcript's line ordering is a fiction. A tool that prints a warning before its first progress line appears in the transcript with that warning after it, and anyone debugging from the transcript is reading events in an order that never happened. Third, warnings are counted by grepping for the literal ': warning: ', so a tool that says WARNING: reports zero and a noisy build looks pristine.


Common Mistakes

  1. Writing 2>&1 > file when you meant > file 2>&1. Redirections are applied left to right and 2>&1 copies descriptor 1's destination as it stands at that moment. The wrong way round, descriptor 2 keeps the terminal and only stdout reaches the file. Nothing warns you, the exit status is unchanged, and the file looks plausible because it is half right.
  1. Putting a space between the digit and the operator. 2 > err.txt is not a stderr redirection. Bash reads 2 as an ordinary argument and > err.txt as a stdout redirection, so the diagnostics still go to the terminal and the program receives a mystery argument.
  1. Expecting a variable set inside a pipeline to survive it. cmd | while read ...; do n=$((n+1)); done runs the loop in a subshell, so n is back to its old value the moment the pipeline ends. Feed the loop with < <(cmd) instead, or enable shopt -s lastpipe.
  1. Reading and writing the same file in one command. sort file > file truncates file before sort ever opens it, because bash performs redirections before running the command. The result is an empty file and no error. Write to a temporary file and move it into place.
  1. Using > twice and wondering where the first half went. cmd1 > log; cmd2 > log truncates log again, leaving only cmd2's output. Use >> for the second write, or open the file once with exec 3> log.
  1. Silencing descriptor 2 to hide one specific message. 2>/dev/null discards everything on that stream, including bash's reports of unbound variables and failed redirections. The noise goes away and so does the diagnosis of the next unrelated bug.
  1. Trusting a pipeline's exit status to mean the first command worked. $? after a | b is b's status, so a failing a piped into a successful grep reports success. Use set -o pipefail, or inspect ${PIPESTATUS[@]} immediately, before another command overwrites it.
  1. Assuming &> file works everywhere. It is a bash extension. Under dash, which is /bin/sh on many Debian-derived systems, it parses as a background job followed by a redirection and does something else entirely. Scripts with a #!/bin/sh shebang must use > file 2>&1.
  1. Forgetting that a here-document's terminator must be alone on its line. An indented EOF ends nothing unless the operator was <<-, and even then only leading tabs are stripped, never spaces. The shell reads to the end of the file looking for it and reports a syntax error whose line number points at the start of the document, not at the indentation that caused it.

Best Practices

  • Prefer &> file in bash scripts and > file 2>&1 in sh scripts. The first cannot be written in the wrong order; the second is portable. Choosing per shebang means never re-deriving the ordering rule under time pressure.
  • Send results to descriptor 1 and everything else to descriptor 2. A function's progress messages and warnings belong on >&2 so callers can capture its real output with $(...) without filtering your commentary out of it.
  • Open a log once with exec rather than appending on every line. exec 3> run.log truncates exactly once and every later >&3 writes through the same open descriptor, removing both the repeated-truncation bug and the per-line open cost.
  • Feed a while read loop that sets variables with redirection, never a pipe. done < <(cmd) keeps the loop in the current shell. Reserve the pipe form for loops that only produce output.
  • Turn on set -o pipefail in any script whose pipelines matter. Without it a pipeline reports only its last stage, and a failed producer feeding a successful consumer looks like a clean run.
  • Redirect into a temporary file and rename it into place. cmd > out.tmp && mv out.tmp out.txt leaves out.txt untouched when cmd fails, where cmd > out.txt destroys the previous version before discovering the failure.
  • Use tee when a stream needs both a reader and a record. cmd 2>&1 | tee run.log | grep -i error keeps the full transcript and filters at once -- and remember the pipeline's status then belongs to grep.
  • Discard on the narrowest scope that works. Redirect the one command whose diagnostics you want gone, not the enclosing block or the whole script, so the next unexpected error still has somewhere to be seen.

Practice Exercises

  1. Prove the ordering rule to yourself. Write a script that prints two lines to stdout and two to stderr and exits 5. Run it four ways -- > a.txt, 2> b.txt, > c.txt 2>&1 and 2>&1 > d.txt -- then print each file's line count and the exit status after each run. Predict all eight numbers on paper first, then check.
  1. Build a two-channel logger. Write a script that opens exec 3> audit.tsv, then runs three commands (one of which fails), writing one tab-separated row per command to descriptor 3 while the commands' own output goes to stdout.log and stderr.log. At the end, read audit.tsv back through exec 4< and print how many rows it holds and how many recorded a non-zero status.
  1. Fix the subshell counter three ways. Start from printf 'a\nb\nc\n' | while IFS= read -r line; do n=$((n + 1)); done and make n equal 3 after the loop using (a) process substitution, (b) shopt -s lastpipe, and (c) a redirection from a temporary file. Print n after each and explain in a comment why the original returned 0.
  1. Repair the build wrapper's real flaw. Take the wrapper from the Real World Example and make summary.tsv survive: write it to a path given on the command line, defaulting to the current directory, rather than into the temporary directory the EXIT trap deletes. Then fix the transcript ordering flaw by having each step write into a single per-step file with &> instead of two files that are later concatenated, and state in a comment what that fix costs you.