Safe header for Bash scripts
Fail fast on errors, unset variables and broken pipes, and clean up temp files with a trap.
- Bash
- GreenSnippets
- MIT
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
tmpdir="$(mktemp -d)"
cleanup() {
rm -rf "$tmpdir"
}
trap cleanup EXIT
main() {
echo "Working in $tmpdir"
# ... your commands here ...
}
main "$@"How it works
By default Bash keeps going after a failing command, which can turn one error into data loss. This header makes scripts stop where things go wrong:
set -eexit when a command failsset -utreat unset variables as errorsset -o pipefaila pipeline fails if any stage failstrap ... EXITruns cleanup on success, failure or Ctrl-C
Quote every variable expansion ("$var"). set -e has quirks inside if conditions and && lists, so it is a safety net, not a substitute for checking important commands.
This script has been reviewed but not run through an automated test.
This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.
Related snippets
- Bash
Parse command-line flags with getopts
Handle -v, -o FILE and -h in a bash script with getopts and a usage message.
- Python Tested
Command-line tool skeleton with argparse
A small CLI with a positional argument, flags, a main function and proper exit codes.
- Bash
Timestamped tar.gz backup that keeps the newest N
Archive a directory with a sortable timestamp and delete older backups beyond a retention count.
- Bash
Delete local Git branches that are already merged
Clean up merged local branches safely, excluding main, master, develop and the current branch.

