Bash: `-su: $*: unbound variable` with `set -u`

bashfreebsd

This is a FreeBSD 7.x system running GNU bash version 4.0.

In Bash, the set -u option can force a shell to print an error if it encounters an unset variable, like this:

$ set -u
$ echo $THISISUNSET
-su: THISISUNSET: unbound variable
$ echo $?
1

However, I am also encountering this same error for $*:

$ echo $*
-su: $*: unbound variable
$ echo $?
1
$ echo $@
-su: $@: unbound variable

The Bash Manual 4.3.1 The Set Builtin specifically says that set -u ignores $* and $@:

-u Treat unset variables and parameters other than the special parameters ‘@’ or ‘*’ as an error when performing parameter expansion.
An error message will be written to the standard error, and a
non-interactive shell will exit.

How can I fix this?

Best Answer

This is a bug in older versions of bash, specifically 4.0​β2 patchlevel d to 4.0 patchlevel m. From the changelog from 4.0 to 4.1​α:

n. Fixed the behavior of set -u to conform to the latest Posix interpretation: every expansion of an unset variable except $@ and $* will cause the shell to exit.

This behavior was introduced in ​4.0β2 because the previous (and now again current) behavior was thought to be buggy:

d. Fixed a bug that caused expansions of $@ and $* to not exit the shell if the -u option was enabled and there were no posititional parameters.

Related Question