Exit Codes

Understanding and using exit codes for error handling and conditional execution in scripts and commands

Exit codes (also called return codes or status codes) are numeric values that programs return to the shell when they finish executing. They indicate whether a command succeeded (0) or failed (non-zero), enabling scripts and system processes to make decisions based on command outcomes.

Key Concepts

  • Success Code: Always 0, indicates successful execution
  • Error Codes: 1-255, indicate various types of failures
  • $? Variable: Shell variable containing the last command’s exit code
  • Signal Termination: Codes 128+ often indicate process killed by signal
  • Command Chaining: Exit codes enable conditional execution

Command Syntax

Exit codes are automatically set by commands, but you can:

  • Check with: echo $?
  • Set manually with: exit [code]
  • Use in conditionals: command && success_action || fail_action

Common Exit Codes

0 - Success/True 1 - General error 2 - Misuse of shell command 126 - Command not executable 127 - Command not found 128+n - Fatal error signal “n” 130 - Script terminated by Ctrl+C

Practical Examples

Example 1: Checking exit codes

1
2
3
4
5
6
7
ls /existing/directory
echo $?
# Output: 0

ls /nonexistent/directory
echo $?
# Output: 2

Demonstrates success vs failure exit codes

Example 2: Using in conditionals

1
2
3
4
5
if grep "pattern" file.txt; then
    echo "Pattern found"
else
    echo "Pattern not found"
fi

Conditional execution based on grep’s exit code

Example 3: Command chaining

1
2
3
4
5
mkdir backup && cp file.txt backup/ && echo "Success"
# Only proceeds if each command succeeds

command1 || echo "Command1 failed"
# Executes echo only if command1 fails

Logical operators using exit codes for flow control

Example 4: Setting custom exit codes

1
2
3
4
5
6
7
#!/bin/bash
if [ $# -eq 0 ]; then
    echo "No arguments provided"
    exit 1
fi
echo "Processing: $1"
exit 0

Script that sets appropriate exit codes

Use Cases

  • Script Error Handling: Check if operations succeeded
  • Automated Systems: Monitor service health
  • CI/CD Pipelines: Determine build success/failure
  • System Monitoring: Alert on command failures
  • Conditional Execution: Run commands based on previous results

echo $? - Display last exit code exit [n] - Set exit code and terminate test or [ - Return exit codes for conditions true - Always returns 0 false - Always returns 1

Tips & Troubleshooting

  • Always check $? immediately after the command
  • Exit codes are overwritten by each new command
  • Use set -e in scripts to exit on any non-zero code
  • Document custom exit codes in your scripts
  • Remember: 0 = success, everything else = failure
  • Some commands use specific codes for different errors
  • Pipeline exit codes reflect the last command unless using set -o pipefail