Most Bash scripts start as five lines and grow until one silent failure costs an afternoon. This is a starter file for new scripts. It fails early, cleans up after itself and tells you which line broke.
The whole file is on GitHub: circuittimes/bash-script-template.
The first three lines
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
-
env bashfinds Bash throughPATH, so the script also runs on systems where Bash is not in/bin. -
-estops on a failed command.-ustops on an unset variable.-o pipefailmakes a pipeline fail when any stage fails, not only the last one. -
-Elets theERRtrap fire inside functions too. - The
IFSline stops word splitting on spaces, which protects file names that contain them.
Clean up on every exit
cleanup() {
local status=$?
if [[ -n "$WORKDIR" && -d "$WORKDIR" ]]; then
rm -rf -- "$WORKDIR"
fi
exit "$status"
}
trap cleanup EXIT
The EXIT trap runs whether the script succeeds, fails or calls exit itself. Saving $? first keeps the original exit status, so a failed run still reports failure after the cleanup.
Say where it broke
on_error() {
log "error: command failed on line $1"
}
trap 'on_error "$LINENO"' ERR
With set -e alone, a script just stops. This trap prints the line number first.
Keep messages off standard output
log() {
printf '%s [%s] %s\n' "$(date +%H:%M:%S)" "$SCRIPT_NAME" "$*" >&2
}
Logs go to standard error. Standard output stays clean, so the script can sit in a pipeline.
What we checked
We ran the template with GNU Bash 5.2.21 on Linux: the success path, a missing argument, an unreadable file and -h. ShellCheck 0.11.0 reports no warnings. We did not run it on the Bash 3.2 that ships with macOS.
A real run looks like this:
12:36:49 [template.sh] debug: working directory is /tmp/tmp.nNapLgQDWW
12:36:49 [template.sh] notes.txt has 3 lines
Going further
Strict mode has edge cases, such as commands that are allowed to fail and local hiding an exit status. Our full guide covers those with examples: Bash scripting tutorial and best practices.
If you spot a problem in the template, open an issue on the repository.
Disclosure: Circuit Times used Claude, an AI model made by Anthropic, to help prepare this post. Circuit Times is responsible for the checks and the conclusions.
Top comments (0)