Exit Status and Error Handling
Write robust scripts that fail early and clean up properly.
Exit status
- 0 = success; non-zero = failure
$?holds the last command’s status
cmd
status=$?
if (( status != 0 )); then echo "failed: $status"; fi
set -euo pipefail
set -euo pipefail
# -e: exit on error
# -u: undefined var is an error
# -o pipefail: pipeline fails if any stage fails
Caveats: -e is disabled in some contexts (subshells, conditionals). Prefer explicit checks where critical.
Traps
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT
Run cleanup on exit (success or error). Add INT/TERM for signals.
ERR trap and functions
set -E # inherit ERR in functions
trap 'echo "error on line $LINENO"' ERR
Guarded commands
rm -rf -- "$dir" || { echo "rm failed"; exit 1; }
Retry pattern
for i in {1..3}; do cmd && break; sleep 1; done
Logging
log() { printf '[%(%F %T)T] %s\n' -1 "$*"; }
Summary
- Check exit codes; enable
-euo pipefailthoughtfully - Use traps for cleanup and
ERRfor diagnostics