Error Handling Methods
Introduction to Error Handling in Linux
Error handling is a critical aspect of robust Linux scripting, ensuring scripts can gracefully manage unexpected situations and provide meaningful feedback.
Error Handling Strategies
graph TD
A[Error Handling] --> B{Error Detection}
B --> C[Logging]
B --> D[Graceful Exit]
B --> E[Error Reporting]
1. Exit Status Handling
#!/bin/bash
## Function with error handling
process_file() {
local file="$1"
if [ ! -f "$file" ]; then
echo "Error: File does not exist" >&2
return 1
fi
## Process file logic here
cat "$file"
return 0
}
## Usage with error checking
process_file "nonexistent.txt"
if [ $? -ne 0 ]; then
echo "File processing failed"
fi
Error Handling Techniques
Technique |
Description |
Example |
Exit Codes |
Numeric values indicating script status |
0 = Success, 1-255 = Error |
Error Streams |
Separate error output from standard output |
>&2 |
Trap Commands |
Catch and handle system signals |
trap command |
2. Advanced Error Handling
#!/bin/bash
## Comprehensive error handling function
safe_command() {
local command="$1"
## Execute command with error tracking
output=$(eval "$command" 2>&1)
status=$?
## Error processing
if [ $status -ne 0 ]; then
echo "Command failed: $command" >&2
echo "Error output: $output" >&2
return $status
fi
echo "$output"
return 0
}
## Usage example
safe_command "ls /non_existent_directory"
Signal Handling
#!/bin/bash
## Trap multiple signals
cleanup() {
echo "Script interrupted. Cleaning up..."
exit 1
}
## Register signal handlers
trap cleanup SIGINT SIGTERM ERR
## Main script logic
while true; do
## Long-running process
sleep 1
done
Error Logging Mechanisms
System Logging
#!/bin/bash
## Logging to syslog
log_error() {
local message="$1"
logger -p user.err "LabEx Script: $message"
}
## Example usage
log_error "Critical error occurred"
Best Practices for Error Handling
- Always check command return status
- Provide clear error messages
- Log errors for debugging
- Implement graceful error recovery
- Use meaningful exit codes
Advanced Error Handling Patterns
#!/bin/bash
## Complex error handling with multiple checks
validate_and_process() {
local input="$1"
## Multiple validation checks
if [ -z "$input" ]; then
echo "Error: Input cannot be empty" >&2
return 1
fi
if [[ ! "$input" =~ ^[0-9]+$ ]]; then
echo "Error: Input must be numeric" >&2
return 2
fi
## Process valid input
echo "Processing: $input"
return 0
}
## Demonstrate error handling
validate_and_process ""
validate_and_process "abc"
validate_and_process "123"
Conclusion
Effective error handling in Linux scripts involves multiple strategies: checking exit statuses, managing error streams, trapping signals, and providing comprehensive logging and reporting mechanisms.