#!/bin/bash # --- Script Configuration --- LOG_FILE="/var/log/my_script.log" SCRIPT_NAME=$(basename "$0") DATE_FORMAT="+%Y-%m-%d %H:%M:%S" # --- Error Handling --- # Exit immediately if a command exits with a non-zero status. set -e # Treat unset variables as an error. set -u # If any command in a pipeline fails, that return code will be used. set -o pipefail # Function to log messages with timestamp and script name log() { local type="$1" local message="$2" echo "$(date "${DATE_FORMAT}") [${SCRIPT_NAME}] [${type}] ${message}" | tee -a "${LOG_FILE}" } # Function to handle errors before exiting error_handler() { local last_command="${BASH_COMMAND}" local last_line="${BASH_LINENO[0]}" log "ERROR" "Script failed at line ${last_line}: '${last_command}'" # You might want to send an alert here exit 1 } # Trap errors and call error_handler trap 'error_handler' ERR # --- Main Script Logic --- log "INFO" "Script started." # Example: Check if a required command exists if ! command -v "jq" &> /dev/null; then log "WARN" "jq command not found. Some functionality might be limited." # Or, make it a critical error: # log "FATAL" "jq command is required but not found. Exiting." # exit 1 fi # Example: Perform a task that might fail log "INFO" "Attempting a critical operation..." # Simulate a failing command: # ls /nonexistent-directory # If 'ls /nonexistent-directory' was uncommented, it would trigger the error_handler due to 'set -e' # Simulate a successful command log "DEBUG" "Listing current directory contents." ls -la | head -n 3 log "INFO" "Operation completed successfully." # Example: Access an unset variable (will trigger error due to 'set -u') # echo "This will fail: ${UNSET_VARIABLE}" log "INFO" "Script finished successfully."