Unbound variable
This error occurs when a script, running with `set -o nounset` or `set -u`, tries to expand a variable that has not been defined. It is a safety feature to prevent unexpected behavior from empty variables.
- 1A variable name is misspelled.
- 2A variable is used before it has been assigned a value.
- 3A script relies on an environment variable that is not set.
A script with `set -u` is called without a required variable being set.
#!/bin/bash set -u # or set -o nounset echo "Hello, $UNDEFINED_VAR" echo "Exit: $?"
expected output
bash: UNDEFINED_VAR: unbound variable Exit: 1
Fix 1
Provide a default value
WHEN A variable is optional
echo "Hello, ${OPTIONAL_VAR:-World}"Why this works
The `${VAR:-default}` parameter expansion provides a default value if the variable is unset or null, avoiding the unbound variable error.
Fix 2
Check if the variable is set
WHEN A variable is required
if [ -z "${REQUIRED_VAR+x}" ]; then
echo "Error: REQUIRED_VAR is not set." >&2
exit 1
fiWhy this works
The `${VAR+x}` expansion produces 'x' if the variable is set, allowing a test with `-z` to see if it is unset.
✕ Remove `set -u`
`set -u` is a valuable tool for writing robust scripts. Removing it hides potential bugs caused by typos or logic errors and can lead to dangerous behavior, like `rm -rf /$UNDEFINED_VAR/`.
GNU Bash Manual
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev