← Knowledge Base
BashReference note1 min read · updated 2026-11-27

A safe header for Bash scripts

set -euo pipefail, a trap for cleanup, and argument checks that make scripts fail loudly instead of silently.

bashscriptingsafety
#!/usr/bin/env bash
set -euo pipefail            # stop on errors, unset variables and failed pipes
IFS=$'\n\t'

tmp=$(mktemp -d)
cleanup() { rm -rf "$tmp"; }
trap cleanup EXIT            # runs on exit, error or Ctrl+C

[[ $# -ge 1 ]] || { echo "usage: $0 <file>" >&2; exit 2; }
file=$1

-e exits on a failing command (but not inside if conditions), -u turns typos in variable names into errors, pipefail makes a | b fail if a fails. Check scripts with shellcheck script.sh (apt install shellcheck); it finds most quoting mistakes.