Skip to content
linux command-line

Exit Code

exit-code exit-status shell scripting troubleshooting
Plain English

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.

Technical Definition

Every process ends with an exit status from 0 to 255, set by exit() or returned from main().

Conventions:

CodeMeaning
0Success
1General error
2Misuse of a command (bad arguments) in many tools
126Found but not executable (permissions)
127Command not found
128+NKilled 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 status
  • cmd1 && cmd2 runs cmd2 only if cmd1 succeeded; cmd1 || cmd2 only if it failed
  • if cmd; then ... tests the exit code, not output
  • set -e makes a script stop at the first failure; set -o pipefail extends 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.

Source: bash(1) Linux manual page, EXIT STATUS

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)
In the Wild

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.