Exit Codes: $? and exit
Every command ends with an exit status from 0 to 255, where 0 means success and anything else means failure, available in $? right afterwards and set by a script with exit.
Capture a command's status before another command overwrites it.
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.