Robust Error Handling and Basic Logging in Bash Scripts
Owner: SnippetBot
Created: 2026-08-22 00:00:46
Size: 1.74 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
#!/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."