Exit Codes: $? and exit
tar fails because the disk is full, prints an error that scrolls away, and backup.sh cheerfully echoes "Backup done". A script cannot read error messages like you do. It reads something simpler: a number every command leaves behind when it finishes.
The rule
Zero means success; any other number, 1 to 255, means failure.
Every command ends with an exit status. Bash keeps the most recent one in $?:
ls ~/notes ; echo $? # 0 the folder exists
ls ~/nothing ; echo $? # a non-zero number, such as 1 or 2This is the reverse of many programming languages, where 0 means false. In the shell, 0 is the one way to succeed and every other number is a different way to fail. Some common ones:
| Status | Usual meaning |
|---|---|
| 0 | success |
| 1 | general failure |
| 2 | misused the command (bad options or arguments) |
| 126 | found but not executable |
| 127 | command not found |
| 130 | stopped by Ctrl-C (128 + signal 2) |
A script sets its own status with exit:
tar -czf "$archive" "$src"
status=$?
echo "tar finished with status $status"
exit "$status"If a script has no exit, its status is that of the last command it ran. Values wrap around at 256, so exit 256 reports 0 and exit 300 reports 44. Keep to 0 to 255.
The shortcut
$? is a one-shot reading: catch it on the very next line or lose it. Every command, even echo, replaces it. So the habit is run, save, use: status=$? straight after the command you care about.
Run the failing command
ls /nopefails and sets$?to a non-zero value.
Drills
Answer fast — trust the rule.
What does false; echo $? print?
You run ls /nope, then echo $?, then echo $? again. What does the second echo print?
You mistype a command, lss, and press Enter. What is $? now?
A script ends with exit 300. What status does its caller see?
A script has no exit line, and its last command is grep finding no match. What is the script's status?
Remember
- Zero means success; 1 to 255 means failure.
$?is one-shot: run, save, use.- A script without
exitreturns its last command's status; end withexiton purpose.
