Exit Code
An exit code is a program’s final verdict, a number it hands back when it finishes. Zero means everything worked. Any other number means something went wrong, and the number can hint at what. You rarely see it, but scripts and tools check it constantly to decide whether to continue or stop.
Every process ends with an exit status from 0 to 255, set by exit() or returned from main().
Conventions:
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | General error |
| 2 | Misuse of a command (bad arguments) in many tools |
| 126 | Found but not executable (permissions) |
| 127 | Command not found |
| 128+N | Killed by signal N: 130 = Ctrl+C (SIGINT), 137 = SIGKILL (often the OOM killer), 143 = SIGTERM |
Individual programs define their own meanings beyond that. grep returns 0 for a match, 1 for no match, 2 for an error. Check the EXIT STATUS section of a man page.
In the shell:
$?holds the last command’s statuscmd1 && cmd2runs cmd2 only if cmd1 succeeded;cmd1 || cmd2only if it failedif cmd; then ...tests the exit code, not outputset -emakes a script stop at the first failure;set -o pipefailextends that to pipelines
Elsewhere: systemd shows it as status=203/EXEC or code=exited, status=1/FAILURE; Docker and Kubernetes report it on stopped containers; CI pipelines fail a job on any non-zero exit.
Checking and using exit codes
$ ls /etc/hostname
/etc/hostname
$ echo $?
0
$ ls /nope
ls: cannot access '/nope': No such file or directory
$ echo $?
2
$ notacommand; echo $?
notacommand: command not found
127
# Only restart if the config test passes
$ sudo nginx -t && sudo systemctl reload nginx
# Why did a service stop?
$ systemctl status myapp | grep "Main PID"
Main PID: 2210 (code=exited, status=137) Exit codes are how automation knows whether to keep going. A script without set -e can fail at step two and cheerfully run steps three to ten on bad data. When a container or service dies, the exit code is the first clue: 137 points at memory limits or the OOM killer, 127 at a missing binary, 126 at permissions. cmd && next is a small habit that prevents a lot of damage.