BASH
Implement Basic Error Handling and Logging in Bash Scripts
Learn to write more resilient Bash scripts by integrating basic error handling with 'set -e', 'trap', and custom logging functions for better debugging and reliability.
#!/bin/bash
# Script with basic error handling and logging
# Configuration
LOG_FILE="script.log"
ERROR_LOG_FILE="script_error.log"
# Enable error detection: exit immediately if a command exits with a non-zero status.
set -e
# Function for logging messages
log_message() {
local level="$1"
local message="$2"
echo "$(date '+%Y-%m-%d %H:%M:%S') [$level] $message" | tee -a "$LOG_FILE"
# For errors, also log specifically to an error file
if [ "$level" == "ERROR" ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S') [$level] $message" >> "$ERROR_LOG_FILE"
fi
}
# Function for exiting gracefully on error
error_exit() {
local message="$1"
log_message "ERROR" "$message" >&2 # Log to both stdout/log and stderr for immediate visibility
echo "Script failed: $message" >&2
exit 1
}
# Trap for unexpected exits (e.g., Ctrl+C, or an error caught by set -e)
# This ensures cleanup or proper error reporting even if an unhandled command fails.
trap 'error_exit "An unexpected error occurred or script was interrupted."' ERR INT TERM
# --- Main Script Logic ---
log_message "INFO" "Script started."
# Example 1: A command that should succeed
echo "Running a successful command..."
ls -l /tmp
log_message "INFO" "Successful command completed."
# Example 2: A command that might fail, explicitly handled
echo "Attempting a command that might fail specifically..."
if ! non_existent_command_example; then # This command will fail
log_message "WARNING" "'non_existent_command_example' failed, but script continues."
# If you wanted to exit here: error_exit "'non_existent_command_example' failed."
fi
log_message "INFO" "Specific command check completed."
# Example 3: A command that will fail and trigger 'set -e' (and thus the trap)
# Uncomment the following two lines to see set -e in action
# log_message "INFO" "Attempting to touch a file in a non-existent path (will trigger error_exit via set -e)"
# touch /nonexistent_path/file.txt # This command will fail and cause script to exit via set -e and trap
log_message "INFO" "Script completed successfully."
exit 0
How it works: This script implements crucial error handling and logging practices for Bash. It uses `set -e` to automatically exit on any command failure, and `trap` to catch various signals (like `ERR` for errors, `INT` for interrupt) to execute a custom `error_exit` function. This function logs detailed messages to a file and `stderr`, ensuring all script failures are properly recorded and reported, enhancing script reliability for deployment or automation tasks.