DEVOPS, SRE AND CLOUD · PART 1 · LINUX, FROM THE INSIDE · SHELL · 12 OF 187

Linux Shell Basics: Pipes, Redirection, Exit Codes

How the shell runs commands: standard input, output and error as file descriptors 0, 1 and 2, redirection with >, >>, 2> and 2>&1, pipes that connect programs (seq 10000000 | wc -l counted ten million lines in 0.114 s in our run), exit codes (0 for success, ls on a missing path gave 2), and why pipefail matters: false | true returns 0 without it and 1 with it.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
1 / 11

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • stdin 0
  • stdout 1
  • stderr 2
  • > >> 2> 2>&1
  • pipes
  • exit codes
  • pipefail
  • && ||

Notes

What the shell does

When you press enter, the shell reads the line, expands variables, wildcards and command substitutions, sets up any redirections and pipes, and starts each program, using the fork and exec system calls from episode one. Then it waits, and stores the program's exit code. A few commands, like cd and export, are builtins that run inside the shell itself, because they must change the shell's own state.

For each command line
  • expand: $VAR, *, ~, $(cmd)
  • set up redirections and pipes
  • fork a child, exec the program
  • wait for it to finish
  • save its exit code in $?
  • builtins (cd, export) run inside the shell itself

Three streams

Every process starts with three open file descriptors. Zero is standard input, normally the keyboard. One is standard output, for normal results. Two is standard error, for error messages and diagnostics. By default all three are connected to your terminal. Keeping errors on a separate stream is what lets you save results to a file while still seeing errors on screen.

Standard streams
  • 0 stdin input (keyboard)
  • 1 stdout normal output
  • 2 stderr errors and logs
  • all three go to the terminal by default
  • they are just file descriptors (episode 1)

Redirection

Redirection points a stream somewhere else. Greater than sends standard output to a file, replacing it; two greater thans append. Two greater than redirects only errors. To capture both, redirect output to a file and then two greater than ampersand one, which means send errors wherever output now goes. The order matters. Less than reads input from a file, and slash dev slash null swallows anything you do not want.

Redirection
cmd > out.txt     stdout, replace
cmd >> out.txt    stdout, append
cmd 2> err.log    stderr only
cmd > all.log 2>&1  both
cmd < in.txt      stdin from file
cmd 2>/dev/null   drop errors

order matters: 2>&1 after >

Pipes

A pipe connects one program's standard output to the next program's standard input. Both run at the same time, with the kernel holding a small buffer between them. We piped ten million numbers from seq into wc minus l, which counts lines. It printed ten million, in a hundred and fourteen milliseconds. Nothing touched the disk. This is how one line of shell can search, filter, count and sort gigabytes of logs.

A pipe (our run)
$ time (seq 10000000 | wc -l)
10000000
real 0m0.114s

both programs run at the
  same time
the kernel buffers between
  them (64 KB by default)

Exit codes

Every program finishes with an exit code. Zero means success, anything from one to two hundred and fifty five means some kind of failure. ls on a missing path returned two in our run. A few codes are worth memorising: one twenty seven means command not found, one twenty six means not executable, one thirty seven means killed by signal nine, and one forty three means stopped by signal fifteen. CI systems, scripts and Kubernetes all decide what to do from this number.

Exit codes (our runs)
$ ls /nope; echo $?
2
$ true; echo $?   → 0
$ false; echo $?  → 1

126 found but not executable
127 command not found
137 killed by SIGKILL (128+9)
143 stopped by SIGTERM (128+15)

The pipeline trap

Now the trap. A pipeline's exit code is only the last command's. False piped into true returned zero in our test, so the failure disappeared. With the option pipefail switched on, the same pipeline returned one. This matters in CI. A curl that fails, piped into jq, can still show green. That is why careful scripts start with strict settings, which part three covers properly.

Our runs
$ false | true; echo $?
0          ← the failure hid
$ set -o pipefail
$ false | true; echo $?
1

curl -s url | jq . passes
  even when curl fails,
  unless pipefail is on

Chaining

Exit codes also drive chaining. Double ampersand runs the next command only if the last one succeeded. Double bar runs it only if the last one failed. A semicolon runs it regardless. Dollar brackets inserts a command's output into another command, and a single ampersand runs something in the background. Make a folder and go into it, or stop the script: that one line protects you from running commands in the wrong place.

Control operators
a && b    b only if a succeeds
a || b    b only if a fails
a ; b     b always
$(cmd)    insert cmd's output
cmd &     run in background

mkdir -p /opt/app &&
  cd /opt/app || exit 1

Common mistakes

Mistakes. Writing two greater than ampersand one before the file redirection, which sends errors to the terminal instead. Ignoring exit codes. Pipelines without pipefail in scripts. Redirecting into the same file you are reading, which empties it before the command starts. Variables without quotes, which break on spaces. And parsing the output of ls, which breaks on unusual file names.

Avoid these
  • cmd 2>&1 > file (wrong order)
  • ignoring exit codes
  • pipelines without pipefail
  • > on the file you are reading (it is emptied first)
  • unquoted "$VAR" with spaces
  • parsing ls output

Say it like this

In the interview: every process starts with standard input, output and error on descriptors zero, one and two. Two greater than ampersand one makes standard error go wherever standard output currently points, so command greater than log, two greater than ampersand one, captures both. A pipe connects one program's output to the next one's input, and since a pipeline returns only the last exit code, scripts set pipefail.

In the interview
  • "Processes start with stdin 0, stdout 1 and stderr 2. 2>&1
  • sends stderr where stdout points, so cmd > log 2>&1 captures both.
  • A pipe joins stdout to stdin. A pipeline returns the last exit
  • code, so scripts set pipefail."

Interview questions

Q1What are stdin, stdout and stderr?

The three standard streams every process starts with, on file descriptors 0 (input), 1 (normal output) and 2 (errors and diagnostics).

Q2What does 2>&1 mean?

Redirect file descriptor 2 (stderr) to wherever descriptor 1 (stdout) currently points; in cmd > file 2>&1 both end up in the file.

Q3What is the difference between > and >>?

> replaces the file's contents (creating it if needed); >> appends to the end, which is what you want for logs.

Q4What does exit code 137 mean?

The process was killed by signal 9 (SIGKILL): 128 + 9. Common after the OOM killer or a forced kill.

Q5What does set -o pipefail do?

Makes a pipeline return a failing status if any command in it fails, not just the last one, so errors are not hidden.

Q6What is the difference between && and ;?

a && b runs b only if a succeeded (exit 0); a ; b runs b regardless of how a ended, so && is safer in scripts.

Q7Why is cd a shell builtin?

A child process cannot change its parent's working directory, so the shell must change its own.

Q8What does exit code 127 mean?

Command not found: usually a PATH problem (common in cron and systemd) or a package that is not installed.