BASH
Implement Robust Error Handling with trap and Logging
Learn to make your Bash scripts more resilient by using `trap` to catch errors and signals, implementing a custom error handler, and logging script execution to a file for better debugging.
#!/bin/bash
# Configuration
LOG_FILE="script.log"
SCRIPT_NAME=$(basename "$0")
# Function to log messages to stdout and a file
log() {
echo "$(date +'%Y-%m-%d %H:%M:%S') [$SCRIPT_NAME] $1" | tee -a "$LOG_FILE"
}
# Function for robust error handling
error_handler() {
local last_command="$BASH_COMMAND"
local line_number="$LINENO"
log "ERROR: Script failed at line $line_number during command: '$last_command'."
log "Exiting due to error."
exit 1
}
# Set trap to call error_handler on any non-zero exit status (error)
trap 'error_handler' ERR
# Set trap to catch common signals for clean exit (e.g., Ctrl+C)
trap 'log "INFO: Script interrupted by user (SIGINT/SIGTERM)."; exit 1' INT TERM
# --- Main Script Logic ---
log "INFO: Script started."
# Example of a successful command
log "INFO: Performing a task (listing directory contents)..."
ls -l /tmp > /dev/null
# Example of a command that might fail (uncomment to test error)
# log "INFO: Attempting a command that will fail..."
# non_existent_command_123
# Example of a command that explicitly exits with an error code (this will trigger the ERR trap)
# log "INFO: Explicitly forcing an error..."
# exit 5
# Another successful command
log "INFO: Another task completed."
# Ensure clean exit if script finishes without error
log "INFO: Script finished successfully."
exit 0
How it works: This script provides robust error handling and logging capabilities. It defines a `log` function to write messages to both standard output and a specified `LOG_FILE`. The `error_handler` function is called when a command exits with a non-zero status (error), printing detailed error information including the line number (`LINENO`) and the failing command (`BASH_COMMAND`). The `trap 'error_handler' ERR` command ensures this function is executed upon any error. Additionally, `trap ... INT TERM` catches interrupt signals (like Ctrl+C), allowing for graceful script termination. This setup makes scripts more reliable and easier to debug in production environments.