BASH
Robust Error Handling and Logging for Bash Scripts
Learn to implement robust error handling, trap signals, and redirect all script output to a log file, ensuring critical operations are reliably monitored and debugged.
#!/bin/bash
# --- Configuration ---
LOG_DIR="/var/log/my_app"
LOG_FILE="$LOG_DIR/script.log"
ERROR_FILE="$LOG_DIR/script_errors.log"
# --- Create log directory if it doesn't exist ---
mkdir -p "$LOG_DIR" || { echo "Failed to create log directory $LOG_DIR. Exiting." >&2; exit 1; }
# --- Redirect all stdout and stderr to log files ---
# tee -a appends output to the file and also prints to console
exec > >(tee -a "$LOG_FILE") 2> >(tee -a "$ERROR_FILE" >&2)
# --- Error Handling Function ---
handle_error() {
local LAST_COMMAND="$BASH_COMMAND"
local LAST_EXIT_CODE="$?"
echo "$(date): ERROR! Command '$LAST_COMMAND' failed with exit code $LAST_EXIT_CODE." >&2
# Optionally perform cleanup or notify
# mail -s "Script Error" [email protected] < "$ERROR_FILE"
exit 1
}
# --- Trap signals for graceful exit and error handling ---
trap 'handle_error' ERR # Catch any command with a non-zero exit status
trap 'echo "$(date): Script interrupted by user (SIGINT)." >&2; exit 1' INT # Catch Ctrl+C
trap 'echo "$(date): Script terminated (SIGTERM)." >&2; exit 1' TERM # Catch kill command
echo "$(date): Script started."
# --- Example Operations ---
echo "Performing a successful operation..."
ls -l /tmp/
echo "Attempting a potentially failing operation (e.g., non-existent directory)..."
ls -l /non_existent_dir/ # This will trigger the ERR trap
echo "This line will not be reached if the previous command fails."
echo "$(date): Script finished."
How it works: This snippet demonstrates how to implement comprehensive error handling and logging in a Bash script. It sets up logging to separate files for standard output and errors, uses `trap` to catch non-zero exit codes (`ERR`), user interruptions (`INT`), and termination signals (`TERM`), ensuring that failures are reported and logged effectively. It also includes an `handle_error` function to centralize error reporting logic.