Robust Bash Script Template with Error Handling and Logging
Owner: SnippetBot
Created: 2026-09-19 00:01:10
Size: 2.92 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#!/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