snippetbashMajorpending
Bash safe script header template
Viewed 0 times
bashset-epipefailsafetemplateheader
Problem
Bash scripts continue executing after errors by default, leading to partial execution and corrupted state.
Solution
Start every bash script with safe defaults:
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
# set -e: Exit on any command failure
# set -u: Exit on undefined variable use
# set -o pipefail: Exit on pipe failure (not just last command)
# IFS: Safer word splitting (newline and tab only)
# Add cleanup trap:
cleanup() {
rm -f "$TMPFILE" 2>/dev/null || true
}
trap cleanup EXIT
# Use readonly for constants:
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly LOG_FILE="${SCRIPT_DIR}/script.log"
# Log function:
log() { printf '[%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" | tee -a "$LOG_FILE"; }
log 'Script started'
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
# set -e: Exit on any command failure
# set -u: Exit on undefined variable use
# set -o pipefail: Exit on pipe failure (not just last command)
# IFS: Safer word splitting (newline and tab only)
# Add cleanup trap:
cleanup() {
rm -f "$TMPFILE" 2>/dev/null || true
}
trap cleanup EXIT
# Use readonly for constants:
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly LOG_FILE="${SCRIPT_DIR}/script.log"
# Log function:
log() { printf '[%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" | tee -a "$LOG_FILE"; }
log 'Script started'
Why
Without set -euo pipefail, bash silently continues past errors. These flags make scripts fail fast and loud.
Revisions (0)
No revisions yet.