Error Handling
Error handling and debugging techniques in Bash
Basic error handling
Basic error handling with set -e and return codes
#!/bin/bash
# Exit on any error
set -e
# Function that might fail
risky_operation() {
if [ $1 -eq 0 ]; then
echo "Success"
else
echo "Error occurred" >&2
return 1
fi
}
# Call with error handling
if risky_operation 1; then
echo "Operation succeeded"
else
echo "Operation failed"
fi
Trap for cleanup
Using trap for automatic cleanup on script exit
#!/bin/bash
# Cleanup function
cleanup() {
echo "Cleaning up..."
rm -f /tmp/temp_file
}
# Set trap for cleanup on exit
trap cleanup EXIT
# Create temp file
touch /tmp/temp_file
echo "Temp file created"
# Script will automatically cleanup on exit
Debug mode
Using set -x for debugging script execution
#!/bin/bash
# Enable debug mode
set -x
# Your script commands
echo "Debug mode enabled"
var="test"
echo "Variable: $var"
# Disable debug mode
set +x
echo "Debug mode disabled"