Code Reference

Exit Codes

Bash · Reference cheat sheet

Exit Codes

Bash · Reference cheat sheet


📋 Overview

Every command returns an 8-bit exit status: 0 success, 1–255 failure. Scripts should exit with meaningful codes. $? holds the last foreground status; with pipefail, pipelines report the rightmost non-zero (or zero if all succeed).

🔧 Core concepts

CodeConvention
0Success
1General error
2Misuse of shell builtins / bad usage (common)
126Found but not executable
127Command not found
128+NFatal signal N (e.g. 130 = SIGINT)
255Out-of-range exit (wrapped)
ToolRole
exit NEnd shell/script with status N
return NEnd function with status N
$?Last status
set -eExit on failure (with caveats)
set -o pipefailPipeline status

sysexits.h codes (EX_USAGE=64, etc.) appear in some tools but are optional for scripts.

💡 Examples

Check and propagate:

if ! git pull; then
  echo "pull failed: $?" >&2
  exit 1
fi

Meaningful script exits:

usage() { echo "usage: $0 <file>" >&2; exit 2; }
[[ $# -eq 1 ]] || usage
[[ -f "$1" ]] || { echo "missing file" >&2; exit 1; }

Capture without losing status:

output="$(cmd)" || status=$?
status=${status:-0}

Pipeline:

set -o pipefail
false | true     # status 1 with pipefail; 0 without

⚠️ Pitfalls

  • exit with values outside 0–255 are truncated modulo 256.
  • cmd || true swallows failures—use only when intentional.
  • set -e is disabled in some contexts (if, &&, ||, !)—know the rules.
  • Assignments: local x=$(false) may not trigger set -e as expected.
  • Background jobs: wait $pid yields that job’s status.
  • Don’t parse $? after another command overwrote it—save immediately.

On this page