0

Does Bash have an option to diagnose (and optionally abort execution) "expanded to empty value" variables?

Example (hypothetical):

$ bash -c 'echo $x' --xxx
bash: line 1: variable 'x' expanded to empty value

Reason for the question: such an option may be useful when debugging scripts.

For example, in some script all variables are expected to expand to a non-empty values. Hence, using an option to detect (and optionally abort execution) "expanded to empty value" variables may be useful for such case.

I've already searched for this option in set builtin, but have found nothing.

0

1 Answer 1

4

All sh shells can make accessing unset variables an error, by running

set -u

The error causes the shell to exit with a non-zero status. When the error occurs in a subshell, only that subshell exits, and it's up to the calling code to propagate the error if it wants to.

Example:

$ bash -c 'echo hello $x world; echo continuing'
hello world
continuing
$ bash -c 'set -u; echo hello $x world; echo continuing'
bash: line 1: x: unbound variable
$ bash -u -c 'echo hello $x world; echo continuing'
bash: line 1: x: unbound variable

I don't think there's any way to apply this to variables that are set to an empty value. That is a weird requirement. What's special about the empty string that makes it less good than any non-empty string?

$ bash -c 'set -u; x=$(true); echo "x ($x) is empty, so what?"'
x () is empty, so what?
2
  • Also note set -o nounset as a more descriptive alternative, common to all POSIX sh implementations (as in the often used (for better or worse) set -o nounset -o errexit -o pipefail (pipefail being a recent addition to POSIX)). Commented Oct 4, 2024 at 15:37
  • Thanks. While reading manual for set builtin I've overlooked -u / nounset.
    – pmor
    Commented Oct 7, 2024 at 11:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.