Error Handling Patterns
Common Error Handling Strategies
1. Conditional Execution
command1 && command2 || command3
2. Try-Catch Simulation
try_command() {
command || {
echo "Error: Command failed"
return 1
}
}
Error Handling Flow Patterns
graph TD
A[Execute Command] --> B{Command Successful?}
B -->|Yes| C[Continue Execution]
B -->|No| D[Error Handling]
D --> E[Log Error]
D --> F[Retry/Fallback]
D --> G[Terminate Script]
Error Handling Techniques
Pattern |
Description |
Use Case |
Short-circuit |
Conditional execution |
Simple error prevention |
Error trapping |
Capture and handle errors |
Complex error management |
Defensive programming |
Validate inputs |
Prevent unexpected failures |
Comprehensive Error Handling Script
#!/bin/bash
## Error logging function
log_error() {
local message="$1"
echo "[ERROR] $(date): $message" >> error.log
}
## Retry mechanism
retry_command() {
local command="$1"
local max_attempts="${2:-3}"
local attempt=1
while [ $attempt -le $max_attempts ]; do
if eval "$command"; then
return 0
fi
log_error "Command failed, attempt $attempt of $max_attempts"
((attempt++))
sleep 2
done
return 1
}
## Error handling wrapper
safe_execute() {
local command="$1"
if ! retry_command "$command"; then
log_error "Failed to execute: $command"
exit 1
fi
}
## Example usage
safe_execute "wget https://example.com/file.txt"
Advanced Error Handling Patterns
validate_input() {
local input="$1"
if [[ -z "$input" ]]; then
echo "Error: Input cannot be empty"
return 1
fi
}
2. Graceful Degradation
perform_task() {
primary_method || {
echo "Primary method failed, using fallback"
fallback_method
}
}
Error Handling Best Practices
- Implement comprehensive error logging
- Use meaningful error messages
- Create retry mechanisms
- Validate inputs
- Provide fallback strategies
Error Classification
graph TD
A[Error Types] --> B[Recoverable Errors]
A --> C[Non-Recoverable Errors]
B --> D[Retry Possible]
B --> E[Fallback Available]
C --> F[Immediate Termination]
C --> G[Critical System Errors]
Key Considerations
- Anticipate potential failure points
- Design robust error handling mechanisms
- Balance between error prevention and user experience
- Use appropriate logging and monitoring
By implementing these error handling patterns, developers can create more resilient and reliable Bash scripts that gracefully manage unexpected situations.