What Is set -u? Failing on Undefined Variables
set -u (nounset) makes the shell treat any reference to an undefined variable as an error, instead of silently substituting an empty string.
By default, using a variable that was never set just yields an empty string, which can lead to disasters like rm -rf "$DIR/" deleting from the root when $DIR is empty. set -u stops that by turning an unset variable into an immediate error. It is the u in set -euo pipefail.
What set -u does
With set -u active, referencing a variable that has no value causes the shell to print an error and exit. This catches typos in variable names and inputs that were never provided.
The danger it prevents
Without set -u, $TYPOED_VAR quietly becomes empty. A path built from an empty variable can point somewhere catastrophic, and a missing required input can let a build run with no configuration.
Catching real bugs
- A misspelled variable name surfaces as an error, not silence.
- A missing required environment variable fails fast.
- Empty-path mistakes are caught before they cause damage.
Providing defaults
When a variable is legitimately optional, use "${VAR:-default}" to supply a fallback. This works with set -u, giving you a value without triggering the unset-variable error.
set -u in CI
CI scripts depend on environment variables and secrets that may be missing in some contexts. set -u makes a missing secret or input fail loudly at the start, instead of producing a broken build that fails in a confusing way later.
Catching missing inputs on managed runners
On Latchkey runners, set -u means a step that expects an environment variable fails immediately if it is absent. Pair it with "${VAR:-}" defaults for truly optional values to keep steps both safe and flexible.
Key takeaways
- set -u makes referencing an unset variable an error instead of an empty string.
- It catches typos and missing required inputs before they cause damage.
- Use
"${VAR:-default}"to provide fallbacks for genuinely optional variables.