BASH
Implementing Basic Script Logging and Error Handling
Learn how to add effective logging to a dedicated log file and implement robust error handling in Bash scripts to monitor execution and debug issues efficiently.
#!/bin/bash
LOG_FILE="/tmp/myscript_$(date +%Y%m%d_%H%M%S).log"
SCRIPT_NAME=$(basename "$0")
# Function to log messages
log() {
local type="$1"
local message="$2"
echo "$(date +'%Y-%m-%d %H:%M:%S') [$type] $SCRIPT_NAME: $message" | tee -a "$LOG_FILE"
}
# Trap errors and exit cleanly
handle_error() {
local last_command="$BASH_COMMAND"
local line_number="$LINENO"
log "ERROR" "Command failed: '$last_command' at line $line_number"
exit 1
}
trap 'handle_error' ERR
set -e # Exit immediately if a command exits with a non-zero status
log "INFO" "Script started."
log "INFO" "Log file: $LOG_FILE"
# Example commands
echo "--- Performing Task 1 ---"
log "INFO" "Attempting to create a temporary directory."
mkdir -p /tmp/my_temp_dir || log "WARNING" "Failed to create /tmp/my_temp_dir, it might already exist."
sleep 1
echo "--- Performing Task 2 ---"
log "INFO" "Attempting to copy a file (simulated)."
cp /etc/hosts /tmp/my_temp_dir/hosts_backup || log "ERROR" "Failed to copy /etc/hosts" # This will trigger the error trap if it fails
sleep 1
# Simulate a command that will fail to demonstrate error handling
echo "--- Performing Task 3 (will fail) ---"
log "INFO" "Attempting a command that will intentionally fail."
# This command will fail because 'non_existent_command' does not exist
non_existent_command "arg" # This line should trigger the trap due to set -e
log "INFO" "This message should not be reached if Task 3 fails and 'set -e' is active."
log "INFO" "Script finished successfully."
How it works: This script sets up basic logging and error handling. The `log` function writes timestamped messages to both `stdout` and a dedicated log file, allowing for real-time monitoring and persistent records. `set -e` ensures the script exits immediately if any command fails. An `ERR` trap is configured to call `handle_error` upon any command failure, which logs the exact command and line number where the error occurred before exiting, making debugging much easier.