Exit Codes & Debugging
Exit Codes
Every command returns an exit status: 0 = success, non-zero = failure. Scripts should exit with a meaningful code.
if ! command -v git >/dev/null; then
echo 'git missing' >&2
exit 1
fi
| Idiom | Meaning | ||
|---|---|---|---|
cmd && echo ok | run echo only if cmd succeeded | ||
| `cmd \ | \ | echo fail` | run echo only if cmd failed |
cmd; echo $? | print last exit code |
Debugging: run with bash -x script.sh or add set -x to trace each line as it executes.
Exam tip: Conventionally exit codes 1-125 are script/command errors, 126 = not executable, 127 = command not found, 130 = terminated by Ctrl+C (128+SIGINT).