set -euo pipefail

View saved

Put it near the top

Many robust scripts start with strict mode after the shebang.

#!/usr/bin/env bash
set -euo pipefail

What each flag does

  • -e — exit when a command fails
  • -u — error on unset variables
  • -o pipefail — pipelines fail if any stage fails

Watch intentional failures

Commands you expect to fail need care under -e. Use if, || true, or temporary set +e deliberately.

if grep -q TODO notes.txt; then
  echo "found TODO"
fi
# grep returns 1 when there is no match

Nounset and defaults

With -u, always provide defaults for optional args: "${1:-}".

name="${1:-world}"
echo "Hi, $name"

Comments

One comment per signed-in account. Comments are saved with this page’s URL.