Most one-off shell scripts never get around to the safety and structure they need, because adding it means retyping the same header every time and you are in a hurry. The fix is to stop retyping it: keep one template and start every script from it.
I have written the same first fifteen lines of Bash hundreds of times, badly and inconsistently, and so has everyone else. A script that works on your laptop then fails silently in production because an unset variable expanded to nothing, or a pipeline swallowed a failure, or a temp file was left behind when it died halfway. None of that is exotic. All of it is preventable with a boilerplate you paste once and forget. Below is the template I actually start from, followed by a reading of why each part earns its place.
The template
This is a complete, runnable skeleton for Bash 5.2. Save it, make it executable with chmod +x, and replace the two comment lines in main() with your actual work.
Free · 4 minutes
Is your engineering team shipping safely, or quietly accumulating risk?
Fourteen questions on how work gets from idea to production — cadence, testing, rollback, and the key-person risk in your delivery. Banded finding on screen, full sheet by email.
#!/usr/bin/env bash
#
# example.sh — one-line description of what this script does.
#
# Start every new script from this file. Run with -h for usage.
set -euo pipefail
IFS=$'\n\t'
# --- Identity and location -------------------------------------------------
# BASH_SOURCE[0] is the script itself even when the file is sourced. The cd
# dance resolves the directory the script lives in, not the caller's cwd.
SCRIPT_NAME="$(basename -- "${BASH_SOURCE[0]}")"
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
readonly SCRIPT_NAME SCRIPT_DIR
# --- Logging ---------------------------------------------------------------
# Colour only when stderr is a real terminal, so cron mails and redirected
# log files stay free of escape codes. Everything goes to stderr, leaving
# stdout clean for the script's actual output.
if [[ -t 2 ]]; then
readonly C_RESET=$'\033[0m' C_RED=$'\033[31m' C_YELLOW=$'\033[33m' C_BLUE=$'\033[34m'
else
readonly C_RESET='' C_RED='' C_YELLOW='' C_BLUE=''
fi
log() { printf '%s[%s] %s%s\n' "$C_BLUE" "$(date +'%H:%M:%S')" "$*" "$C_RESET" >&2; }
warn() { printf '%s[warn] %s%s\n' "$C_YELLOW" "$*" "$C_RESET" >&2; }
err() { printf '%s[error] %s%s\n' "$C_RED" "$*" "$C_RESET" >&2; }
die() { err "$*"; exit 1; }
# --- Cleanup ---------------------------------------------------------------
# Runs on every exit path: success, error, or Ctrl-C. Put temp-file removal
# and other teardown here, so a script that dies mid-run still tidies up.
cleanup() {
local -r rc=$?
[[ -n "${TMP_DIR:-}" ]] && rm -rf -- "$TMP_DIR"
exit "$rc"
}
trap cleanup EXIT
# --- Usage -----------------------------------------------------------------
usage() {
cat <<EOF
Usage: $SCRIPT_NAME [-v] [-o OUTPUT] -f FILE
-f FILE Input file to process (required).
-o OUTPUT Where to write results (default: stdout).
-v Verbose logging.
-h Show this help and exit.
EOF
}
# --- Main ------------------------------------------------------------------
main() {
local file='' output='' verbose=0
while getopts ':f:o:vh' opt; do
case "$opt" in
f) file="$OPTARG" ;;
o) output="$OPTARG" ;;
v) verbose=1 ;;
h) usage; exit 0 ;;
:) die "Option -$OPTARG requires an argument (try -h)." ;;
\?) die "Unknown option: -$OPTARG (try -h)." ;;
esac
done
shift $((OPTIND - 1))
[[ -n "$file" ]] || { usage >&2; die "Missing required -f FILE."; }
[[ -r "$file" ]] || die "Cannot read file: $file"
# A temp directory that cleanup() will remove for us.
TMP_DIR="$(mktemp -d)"
(( verbose )) && log "Processing $file in $TMP_DIR"
# ... the real work goes here ...
log "Done."
}
main "$@"
What strict mode buys you, and what it doesn’t
The first two lines are the point of the whole exercise. set -euo pipefail is three separate settings bundled together. -e (errexit) tells the shell to stop when a command fails instead of ploughing on. -u (nounset) turns a reference to an unset variable into an error rather than an empty string — the single most common way a script does something catastrophic like rm -rf "$DIR/" when $DIR was never set. -o pipefail makes a pipeline fail if any stage fails, not just the last one, so curl ... | tar ... no longer reports success when the download died.
The IFS=$'\n\t' line resets the internal field separator to just newline and tab, dropping the space. This makes unquoted expansions split on lines rather than on every space, which is far closer to what you usually mean when iterating over filenames. It is a seatbelt, not an excuse to stop quoting your variables.
Be honest about the limits. set -e is famously full of exceptions: it does not trigger inside a command used in an if condition, inside && or || chains, or in a function called in those contexts. It is a strong default, not a guarantee, which is exactly why the template also has an explicit die() and checks its own preconditions rather than trusting -e to catch everything.
Reading the rest, top to bottom
The location block. ${BASH_SOURCE[0]} is the path to the script itself, and it keeps working even when the file is sourced rather than executed, where $0 would not. The cd … &> /dev/null && pwd pattern turns whatever relative path the script was invoked with into a stable absolute directory, so a script can find files next to it regardless of the caller’s working directory. Assigning first and marking readonly on a separate line is deliberate: combining them hides the exit status of the command substitution, a warning your linter will flag.
The logging block. Everything is written to stderr, which keeps stdout clean for the script’s real output so it can be piped or captured without log lines contaminating it. The colour codes are only defined when stderr is attached to a terminal, tested with [[ -t 2 ]]. This is the detail that stops your logs filling with raw \033[31m escape sequences when the output is redirected to a file — and it is one of the reasons a script that looks fine by hand can behave differently under cron, where there is no terminal at all. If you have ever chased that difference, the mechanics are the same ones I covered in why a Bash script works by hand but fails in cron.
The cleanup trap. trap cleanup EXIT registers a function that runs on every way out of the script — normal completion, an error under set -e, or an interrupt. Capturing $? as the first line of cleanup() and re-exiting with it preserves the original exit code, so the teardown does not mask a failure. This is where temp-file removal belongs; the template pairs it with mktemp -d in main() so a directory is created and guaranteed to be removed even if the script dies mid-run. That guarantee is the whole subject of Bash traps and mktemp, and it is worth reading if you handle anything sensitive in scratch space.
Usage and argument parsing. usage() is a single here-document, so there is exactly one place to update when options change. The getopts loop uses a leading colon in ':f:o:vh' to switch on silent error reporting, which gives you the : case for a missing argument and the \? case for an unknown flag, each producing a clear message instead of Bash’s terse default. After the loop, shift $((OPTIND - 1)) drops the parsed options so any positional arguments are left in place. The required-flag check afterwards fails fast with a readable error rather than crashing three functions deep.
The main() call at the very bottom. Wrapping the logic in a function and calling main "$@" as the last line means the whole file is parsed before anything runs. If you truncate the script mid-download — the classic curl | bash hazard — a partial file will not execute half a command, because execution only begins once the parser has reached that final line.
Keep it honest with a linter
A template gives you a good starting point; it does not keep the code good as it grows. The moment a script is worth keeping, it is worth running through ShellCheck and shfmt so quoting mistakes and the subtler set -e traps are caught before they ship. I would wire that in from the first commit rather than retrofitting it — the setup is in ShellCheck and shfmt as a pre-commit gate. Between a strict-mode template and a linting gate, most of the ways a shell script quietly goes wrong are closed off before you have written a single line of your own logic.
The reason none of this normally gets added is that it feels like overhead on a five-line script. It is not. The five-line script is exactly the one that grows to fifty, gets scheduled, and then fails at three in the morning with no log and a half-written temp file. Start from the template, and the version that fails at three in the morning at least tells you why.
Free interactive tool
Website compliance checklist
What your site has to do, based on what it actually does
Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.
Everything that applies
Ordered by what to do first: legal requirements you can close quickly, then larger pieces of work, then what is expected rather than required. Not exhaustive, and not a legal audit.
Dated PDF, yours to keep or circulate.
Most technology problems are not technology problems. They are control problems.
The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.