Shell Exit Code Methods
Direct Exit Code Retrieval
Using $? Variable
The most common method to retrieve exit codes in shell scripting is the $?
variable:
## Basic $? usage
ls /etc
echo $? ## Typically returns 0 for successful execution
## Failed command example
cat /nonexistent
echo $? ## Returns non-zero exit code
Conditional Execution Methods
AND (&&) Operator
Executes next command only if previous command succeeds:
## Conditional execution
mkdir /tmp/test && echo "Directory created successfully"
OR (||) Operator
Executes next command only if previous command fails:
## Fallback execution
ls /nonexistent || mkdir /tmp/fallback
Advanced Exit Code Handling
Exit Code Comparison
graph TD
A[Command Execution] --> B{Exit Code Check}
B --> |Exit Code == 0| C[Success Path]
B --> |Exit Code != 0| D[Error Handling]
Comprehensive Error Handling Script
#!/bin/bash
## Function to handle different exit codes
check_exit_code() {
case $1 in
0) echo "Operation successful" ;;
1) echo "General error" ;;
126) echo "Permission problem" ;;
127) echo "Command not found" ;;
*) echo "Unknown error with code $1" ;;
esac
}
## Example usage
ls /etc
check_exit_code $?
Exit Code Mapping
Exit Code Range |
Typical Meaning |
0 |
Successful execution |
1-5 |
Generic error conditions |
10-20 |
Application-specific errors |
126-128 |
Execution environment errors |
Practical Techniques
Capturing Complex Exit Codes
## Capturing multiple command exit codes
(command1 && command2) || handle_error
With LabEx, you can explore and master these shell exit code techniques to build robust and reliable scripts.