Frequently Asked Question

What are exit codes and why do they matter?

Every program that finishes in Unix returns a small integer called the exit code or exit status. Zero means success; any non-zero value (1–255) means some kind of failure. The shell stores the most recent exit code in the special variable $?, and uses it for everything: if cmd; then ... tests whether cmd returned zero, cmd1 && cmd2 only runs cmd2 if cmd1 succeeded, and pipelines and set -e all hinge on the same convention. Inside a script, exit 0 declares success and exit 1 (or any non-zero) declares failure.

Conventions exist for some non-zero values. 127 means "command not found", 126 means "found but not executable", 130 means killed by Ctrl+C (signal 2; the shell encodes signal N as 128 + N). Beyond that, programs choose their own meanings, grep returns 1 when it found nothing and 2 on a real error. Designing your script to set meaningful exit codes is what lets it compose cleanly with other tools in pipelines and Makefiles.

Video

Further reading and video