set -u

set -u: Treat Unset Variables as Errors

What it does: Makes bash exit with an error when you reference an undefined variable, catching typos and uninitialized variables.

set -u
echo "$TYPO_VARIABLE"  # Error: unbound variable (instead of silently empty)

The Main Gotcha

You can't use traditional empty-checking patterns:

set -u

# 💥 FAILS - errors before the test runs
if [[ -z "$MAYBE_UNSET" ]]; then
    echo "It's empty"
fi

# ✅ WORKS - use parameter expansion with default
if [[ -z "${MAYBE_UNSET:-}" ]]; then
    echo "It's empty or unset"
fi

The :- provides a default value (empty string) if the variable is unset, preventing the error.

When to Use It

Good for new scripts: Starting fresh with set -u enforces discipline - you explicitly handle all variables from the start.

Hard for existing code: Retrofitting set -u into existing scripts/environments is painful. You'll need to:

  • Add :- to hundreds of variable expansions
  • Initialize all variables that might be unset
  • Fix assumptions that unset equals empty
  • Handle positional parameters ($1, $2) defensively

Common Patterns

# Positional parameters
echo "${1:-default}"           # Default value if no argument

# Required variables  
: "${REQUIRED:?Error: REQUIRED must be set}"

# Optional variables
OPTIONAL="${OPTIONAL:-}"       # Initialize as empty if unset

Bottom line: Great for catching bugs in new code, but retrofitting it into existing systems often isn't worth the effort.


Backlinks