iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

set -euo pipefail

Bash strict mode catches the bugs that would otherwise survive code review and bite in production - unset variables, silent failures, pipe errors.

Bash unofficial strict mode

EXAMPLE
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'

# -e  exit on any command failure (non-zero exit)
# -u  treat unset variables as an error
# -o pipefail  fail the whole pipeline if any command in it fails
# -E  ERR trap inherited by functions, subshells, command substitutions
# IFS  forbid splitting on spaces, only newline + tab

# Traps for cleanup and diagnostics
cleanup() {
  local code=$?
  rm -rf -- "${tmpdir-}"
  exit "$code"
}
trap cleanup EXIT
trap 'echo "ERROR on line $LINENO" >&2' ERR

# Default values for optional vars
: "${LOG_LEVEL:=info}"
: "${BASE_URL:?BASE_URL must be set}"

# Safer parameter expansion
file="${1:-}"
[[ -z $file ]] && { echo 'usage: $0 <file>' >&2; exit 1; }
[[ -f $file ]] || { echo "not a file: $file" >&2; exit 1; }

# Quote everything
while IFS=, read -r name email; do
  echo "hello, $name"
done < "$file"

# Arrays beat string concatenation
args=(--config=prod.json --workers=4)
some-tool "${args[@]}" "$file"

# Bypass set -e for one command without losing the trap
if ! optional-step; then
  echo 'optional step failed - continuing' >&2
fi

# Substitution that can fail safely
hash=$(git rev-parse HEAD || echo unknown)
echo "version: $hash"

Why it matters

Without strict mode every typo becomes a silent failure - cd \$missing_var becomes cd / and rm -rf builds disaster. Always start scripts with set -Eeuo pipefail; pair it with shellcheck and you eliminate most of the historical reasons bash has a bad reputation.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
set -euo pipefail
# -e exit on error, -u error on unset var, -o pipefail catch pipeline errors
Try it Yourself »

Exercise

Recommended strict flags line.

set

Test yourself

Q1. Recommended top of a bash script is…
Q2. -e flag means…
Q3. -u flag errors on…

Discussion

Loading…