bash check exit code of last command — $?

# Run a command
ls /nonexistent
echo $?   # 2 — ls failed (No such file or directory)

# Success check
if [ $? -eq 0 ]; then
  echo "success"
else
  echo "failed"
fi

Every command exits with a numeric code. 0 = success, 1-255 = failure. $? holds the last exit code.

Capture exit code immediately

$? is overwritten by every command. Save it to a variable if you need it later.

some_command
exit_code=$?

echo "did other stuff"

if [ $exit_code -ne 0 ]; then
  echo "some_command failed with code $exit_code"
fi

Common exit codes

# 0   success
# 1   general error
# 2   misuse of shell builtins (e.g. missing argument)
# 126 command found but not executable
# 127 command not found
# 128 invalid argument to exit
# 130 terminated by Ctrl+C (128 + signal 2)

Inline conditional on exit code

# Run b only if a succeeds
command_a && command_b

# Run b only if a fails
command_a || command_b

# Run b regardless
command_a; command_b