Writing Robust Scripts (set -euo)

💤0
Lv 10 XP
← ⚙️ Scripting & Automation · Bash

Writing Robust Scripts (set -euo)

Advanced ⭐ 120 XP ⏱ 18 min #bash#robustness#safety

Make scripts fail fast and safe with strict mode, traps, and quoting discipline.

📖Theory

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 fails
  • set -u — error on use of an unset variable (catches typos)
  • set -o pipefail — a pipeline fails if any stage fails, not just the last
  • IFS=$'\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.

🌍Real-World Example
#!/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"
✍️Hands-On Exercise
  1. Add set -euo pipefail to an existing script and fix anything it now flags.
  2. Use trap to delete a temp file whether the script succeeds or fails.
  3. Demonstrate how set -u catches a misspelled variable name.
  4. Explain why pipefail matters in false | tee log.
🧾Cheat Sheet
SettingEffect
set -eExit on any error
set -uError on unset variable
set -o pipefailFail if any pipe stage fails
set -xPrint commands (debug)
trap fn EXITRun cleanup on exit
mktempSafe 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.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type