1
BashERRORCriticalScriptingHIGH confidence

Unbound variable

What this means

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.

Why it happens
  1. 1A variable name is misspelled.
  2. 2A variable is used before it has been assigned a value.
  3. 3A script relies on an environment variable that is not set.
How to reproduce

A script with `set -u` is called without a required variable being set.

trigger — this will error
trigger — this will error
#!/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

Provide a default value
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

Check if the variable is set
if [ -z "${REQUIRED_VAR+x}" ]; then
  echo "Error: REQUIRED_VAR is not set." >&2
  exit 1
fi

Why this works

The `${VAR+x}` expansion produces 'x' if the variable is set, allowing a test with `-z` to see if it is unset.

What not to do

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/`.

Sources

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Bash errors