Skip to content

bash: unbound variable – aborted by set -u

Linuxtested on Bash 5.3, Ubuntu 26.04

With set -u, Bash aborts as soon as an unset variable is used. Without -u, ${ZIEL}/kopie would simply become /kopie – and the script would carry on in the wrong directory.

Symptom

bash -euc 'echo "${ZIEL}/kopie"'; echo "Exit: $?"
bash: line 1: ZIEL: unbound variable
Exit: 1

-u in bash -euc equals set -u in a script.

Diagnosis

The safety switches compared – pipefail shows what would go unnoticed without protection.

bash -ec 'grep -c x /gibtsnicht 2>/dev/null | sort; echo weiter'; echo "Exit: $?"
bash -ec 'set -o pipefail; grep -c x /gibtsnicht 2>/dev/null | sort; echo weiter'
echo "Exit: $?"
weiter
Exit: 0
Exit: 2

Causes

ZIELVariable never set

A typo in the name, a missing argument or an environment variable that does not exist in the calling context (cron, systemd).

-uset -u is on

The abort is intended: without -u the script would continue with an empty value, which is dangerous for paths.

Fix

Set the variable before use or give a default or an error message, for example ${ZIEL:-/tmp} or ${ZIEL:?missing}.

Don't: Remove set -u to make the error go away. Next time the script will silently work with an empty path.

▶
Break it yourself and find it – free
Shell scripting hands-on, Day 1: the first robust script with set -euo pipefail and ShellCheck.
Go to day 1 →

FAQ

What does set -o pipefail add?

A pipe fails if any part fails – not just the last one. Without pipefail only sort counts in the example, and it always succeeds.

Does every shell have pipefail?

set -e and set -u exist everywhere; pipefail has been standard since POSIX 2024, older sh such as dash before 0.5.13 lack it.

Related error patterns

More