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
|
|
Demonstrates success vs failure exit codes
Example 2: Using in conditionals
|
|
Conditional execution based on grep’s exit code
Example 3: Command chaining
|
|
Logical operators using exit codes for flow control
Example 4: Setting custom exit codes
|
|
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
Related Commands
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 -ein 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