#!/bin/bash # Configuration LOG_FILE="script.log" SCRIPT_NAME=$(basename "$0") # --- Functions --- # Function to display script usage usage() { echo "Usage: $SCRIPT_NAME [OPTIONS]" echo "Options:" echo " -h, --help Show this help message" echo " -v, --verbose Enable verbose output" echo " -a, --action Specify an action (e.g., 'deploy', 'cleanup')" exit 0 } # Function for logging messages log() { local message="$1" local level="${2:-INFO}" # Default level is INFO timestamp=$(date +"%Y-%m-%d %H:%M:%S") echo "$timestamp [$level] $message" | tee -a "$LOG_FILE" >&2 } # Function to handle errors error_handler() { local exit_code="$?" local line_num="$1" local command="$2" if [ "$exit_code" -ne 0 ]; then log "ERROR: Command '$command' failed with exit code $exit_num on line $line_num." ERROR log "Script failed. Check $LOG_FILE for details." ERROR exit "$exit_code" fi } # --- Main Script Logic --- # Enable strict mode: # -e: Exit immediately if a command exits with a non-zero status. # -u: Treat unset variables as an error when substituting. # -o pipefail: The return value of a pipeline is the status of the last command to exit with a non-zero status, # or zero if no command exited with a non-zero status. # -E: ERR traps are inherited by shell functions. set -euo pipefail set -E trap 'error_handler $LINENO "$BASH_COMMAND"' ERR VERBOSE=false ACTION="" # Parse command-line arguments while (( "$#" )); do case "$1" in -h|--help) usage ;; -v|--verbose) VERBOSE=true log "Verbose output enabled." DEBUG ;; -a|--action) if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then ACTION="$2" shift else log "Error: Argument for $1 is missing." ERROR usage fi ;; *) log "Error: Invalid argument '$1'." ERROR usage ;; esac shift done log "Starting $SCRIPT_NAME..." if [ "$VERBOSE" = true ]; then log "Verbose mode is ON." DEBUG fi if [ -n "$ACTION" ]; then log "Action specified: $ACTION" case "$ACTION" in deploy) log "Performing deployment tasks..." INFO # Add deployment logic here log "Deployment complete." INFO ;; cleanup) log "Performing cleanup tasks..." INFO # Add cleanup logic here log "Cleanup complete." INFO ;; *) log "Error: Unknown action '$ACTION'." ERROR usage ;; esac else log "No specific action provided. Running default tasks." INFO # Add default script logic here echo "Hello, web developer!" # Example command that might fail # ls no_such_directory fi log "$SCRIPT_NAME finished successfully." exit 0