Writing Robust Scripts (set -euo)
Make scripts fail fast and safe with strict mode, traps, and quoting discipline.
By default Bash plows ahead after errors, which is dangerous in automation. Strict mode makes scripts fail fast:
set -e— exit immediately if any command failsset -u— error on use of an unset variable (catches typos)set -o pipefail— a pipeline fails if any stage fails, not just the lastIFS=$'\n\t'— safer word-splitting
Add a trap to clean up temp files on exit, always quote variables, and use
mktemp for temporary files. These habits separate a script that silently
corrupts data from one you can trust in production.
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
tmp="$(mktemp)"
cleanup() { rm -f "$tmp"; }
trap cleanup EXIT # always runs, even on error
: "${API_URL:?Must set API_URL}" # fail with a message if unset
curl -fsS "$API_URL" > "$tmp" # -f makes curl fail on HTTP errors
echo "Downloaded $(wc -l < "$tmp") lines" - Add
set -euo pipefailto an existing script and fix anything it now flags. - Use
trapto delete a temp file whether the script succeeds or fails. - Demonstrate how
set -ucatches a misspelled variable name. - Explain why
pipefailmatters infalse | tee log.
Cheat Sheet▾
| Setting | Effect |
|---|---|
set -e | Exit on any error |
set -u | Error on unset variable |
set -o pipefail | Fail if any pipe stage fails |
set -x | Print commands (debug) |
trap fn EXIT | Run cleanup on exit |
mktemp | Safe temp file |
"${VAR:?msg}" | Require a variable |
Common Interview Questions▾
What does set -euo pipefail do?
-e exits on any failure, -u errors on unset variables, and pipefail makes a pipeline fail if any stage fails. Together they make scripts fail fast instead of silently continuing in a broken state.
Why use trap in a script?
To run cleanup (removing temp files, releasing locks) reliably on exit — including when the script errors out — so it doesn’t leave a mess behind.
Why is pipefail important?
Without it, a pipeline’s exit status is only the last command’s, so an early failure (like a failed download piped into a writer) goes unnoticed.