Skip to content

The shell, pipes and exit codes

BasicsConcept

You chain commands with | and check $?, but what is actually wired to what? Here are the three streams every program gets, what a pipe joins, and how a script tells success from failure.

01 Every program starts with three streams

A program run from a shell does not open the keyboard or the screen itself. It is handed three already-open streams, numbered 0, 1 and 2. By default all three point at your terminal, which is why input and output both appear there.

The standard streams
NumberNameUsed forDefault
0stdininput the program readsthe keyboard
1stdoutthe program’s real outputthe terminal
2stderrerrors and progress messagesthe terminal

The program just reads 0 and writes 1 and 2. The shell decides what they are connected to before the program starts: a file, another program, or the terminal. That is the whole idea behind redirects and pipes.

02 What | really connects

a | b asks the kernel for a pipe: a small buffer with a write end and a read end. The shell connects a’s stdout to the write end and b’s stdin to the read end, then starts both. Here is a three-stage pipeline counting error lines in a three-line log.

cat app.log | grep ERR | wc -l
Step 1 of 9
app.log
ok 1
ERR disk
ERR net
pipe 1 · cat → grep
Empty
pipe 2 · grep → wc -l
Empty
  • not read yet
  • read by cat
  • just written

The shell starts all three programs at the same time and joins them with two pipes. Both pipes are empty; nothing has been read yet.

0 wc has counted

Two things to notice. The programs run side by side, not one after the other: wc was already waiting before grep produced anything. And a pipe has a fixed size (64 KiB by default on Linux). A writer that fills it is paused until the reader catches up, so a fast producer cannot flood a slow consumer.

03 stderr skips the pipe

A pipe connects stdout only. Error messages go to stderr, which still points at the terminal, so they appear on screen and the next program never sees them. That is on purpose: errors should not end up mixed into your data.

Shell
$ ls /nope app.log | wc -l
ls: cannot access '/nope': No such file or directory
1

wc counted one line: the name app.log. The error went past the pipe straight to you. To move streams yourself, use redirects. The number before > says which stream.

Common redirects
You writeIt means
cmd > out.txtstdout to a file, replacing it
cmd >> out.txtstdout to a file, appending
cmd 2> err.txtstderr to a file
cmd 2> /dev/nullthrow stderr away
cmd > all.txt 2>&1stdout to a file, then stderr to wherever stdout points now
cmd < in.txtstdin from a file

2>&1 means “make stream 2 point where stream 1 points right now”. The shell applies redirects left to right, so the order changes the result.

Stderr to the terminal
$ ls /nope app.log 2>&1 > out.txt
ls: cannot access '/nope': No such file or directory
# 2 copied stdout while it was still the terminal
Both in the file
$ ls /nope app.log > out.txt 2>&1
$ cat out.txt
ls: cannot access '/nope': No such file or directory
app.log

04 Exit codes and $?

When a program ends it returns a small number to the shell, its exit status. 0 means success. Anything from 1 to 255 means some kind of failure, and each program documents its own meanings. The shell keeps the status of the last command in $?.

Shell
$ grep ERR app.log > /dev/null; echo $?
0
$ grep WARN app.log; echo $?
1
$ grep ERR /missing; echo $?
grep: /missing: No such file or directory
2

grep is a good example: 0 means it found a match, 1 means it found none, 2 means a real error. A status above 128 usually means the program was killed by a signal, and the signal number is the status minus 128: 130 is Ctrl-C (SIGINT, signal 2) and 137 is SIGKILL (signal 9).

Scripts use the status to decide what to do next. a && b runs b only if a succeeded. a || b runs b only if a failed.

Shell
make build && ./deploy.sh
grep -q ERR app.log || echo "no errors today"

05 A pipeline’s status is its last command’s

By default the exit status of a | b | c is the status of c alone. A failure earlier in the pipeline is hidden. In bash, set -o pipefail changes that: the pipeline then fails if any stage fails. Bash also keeps every stage’s status in the PIPESTATUS array.

Shell
$ false | true; echo $?
0
$ set -o pipefail
$ false | true; echo $?
1
$ grep WARN app.log | sort; echo "${PIPESTATUS[@]}"
1 0

curl -s $URL | tar xz in a script reports success even when the download failed, because only tar counts. Put set -o pipefail (often as set -euo pipefail) at the top of bash scripts that run unattended.

06 When it bites

cmd; echo done; echo $?$? is overwritten at once$? holds the status of the last command, and echo is a command too. Save it straight away: cmd; status=$?.
sort data.txt > data.txtReading and writing the same fileThe shell empties data.txt for the > before sort starts, so sort reads an empty file. Write to a new file and rename it.
set -e; grep -c WARN app.loggrep finding nothing stops the scriptWith set -e, a status of 1 from grep ends the script, even though “no match” may be fine. Add || true when no match is acceptable.
yes | head -1 # status 141SIGPIPE under pipefailWhen head exits early, the writer gets SIGPIPE on its next write and dies with status 141 (128 + 13). With pipefail on, that harmless early stop counts as a failure.

07 Check yourself

Question

You run ./build.sh | tee build.log. The build fails with status 1, tee works fine. In bash without pipefail, what is $??

Question

Which line sends both stdout and stderr of cmd into log.txt?

Question

In find / -name x | wc -l, find prints lots of “Permission denied” lines. Does wc count them?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?