Skip to content
GreenSnippets

Safe header for Bash scripts

Fail fast on errors, unset variables and broken pipes, and clean up temp files with a trap.

Bash
#!/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 -e exit when a command fails
  • set -u treat unset variables as errors
  • set -o pipefail a pipeline fails if any stage fails
  • trap ... EXIT runs 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.