BASH
Robust Error Handling and Logging
Enhance your bash scripts with robust error handling and logging capabilities, ensuring critical failures are caught and reported clearly.
#!/bin/bash
# --- Configuration ---
LOG_FILE="/tmp/myscript.log"
# --- Functions ---
# Log messages to stdout and file
log_message() {
local TYPE="$1"
local MESSAGE="$2"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $TYPE: $MESSAGE" | tee -a "$LOG_FILE"
}
# Handle errors and exit
error_exit() {
log_message "ERROR" "$1"
exit 1
}
# --- Script Setup ---
# Exit immediately if a command exits with a non-zero status.
set -e
# Treat unset variables as an error when substituting.
set -u
# Use 'pipefail' to catch errors in pipes.
set -o pipefail
# --- Main Script Logic ---
log_message "INFO" "Script started."
# Example 1: A successful command
echo "Performing step 1..."
sleep 1
log_message "INFO" "Step 1 completed successfully."
# Example 2: A command that might fail
# Let's intentionally make 'cat' fail if the file doesn't exist
NON_EXISTENT_FILE="/tmp/this_file_does_not_exist_$(date +%s).txt"
log_message "INFO" "Attempting to read $NON_EXISTENT_FILE..."
# Use a subshell or check '$?' immediately after a potentially failing command
# if you don't want 'set -e' to exit prematurely, or if you want custom handling.
# For 'set -e' to work as expected, ensure the command is not part of a '&&' or '||' list,
# or the condition of an 'if' statement, unless you expect the error.
cat "$NON_EXISTENT_FILE" || error_exit "Failed to read $NON_EXISTENT_FILE"
# This line will not be reached if cat failed due to 'set -e' or 'error_exit'
log_message "INFO" "Script finished successfully."
exit 0
How it works: This script demonstrates robust error handling and logging using several best practices. `set -e`, `set -u`, and `set -o pipefail` ensure that the script exits on errors, unset variables, or failed commands within pipes. It includes custom `log_message` and `error_exit` functions to consistently write timestamped messages to both standard output and a log file, making debugging easier and script behavior more predictable.