The shell, pipes and exit codes
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.
| Number | Name | Used for | Default |
|---|---|---|---|
| 0 | stdin | input the program reads | the keyboard |
| 1 | stdout | the program’s real output | the terminal |
| 2 | stderr | errors and progress messages | the 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.
- 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.
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.
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.
| You write | It means |
|---|---|
| cmd > out.txt | stdout to a file, replacing it |
| cmd >> out.txt | stdout to a file, appending |
| cmd 2> err.txt | stderr to a file |
| cmd 2> /dev/null | throw stderr away |
| cmd > all.txt 2>&1 | stdout to a file, then stderr to wherever stdout points now |
| cmd < in.txt | stdin 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.
$ ls /nope app.log 2>&1 > out.txtls: cannot access '/nope': No such file or directory# 2 copied stdout while it was still the terminal
$ ls /nope app.log > out.txt 2>&1$ cat out.txtls: cannot access '/nope': No such file or directoryapp.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 $?.
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.
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.
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.