Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Work-around for $@ unbound variable in Bash 4.0.0?

Tags:

bash

shell

sh

bash4

In specifically Bash version 4.0.0, is there any way to work around the use of an empty $@ raising an unbound variable error when set -u is enabled?

Consider the following:

#!/usr/bin/env bash-4.0.0-1

set -xvu

echo "$BASH_VERSION"
echo "${BASH_VERSINFO[@]}"

main () {
  printf '%q\n' "${@:-}"
}

main "${@:-}"

Gives me the following output when I provide an empty set of arguments:

[email protected]:~ $ ./test.sh

echo "$BASH_VERSION"
+ echo '4.0.0(1)-release'
4.0.0(1)-release
echo "${BASH_VERSINFO[@]}"
+ echo 4 0 0 1 release x86_64-unknown-linux-gnu
4 0 0 1 release x86_64-unknown-linux-gnu

main () {
  printf '%q\n' "${@:-}"
}

main "${@:-}"
./test.sh: line 12: $@: unbound variable

I only see this behaviour in Bash version 4.0.0.

I was hoping that using variable substitution ${@:-} would allow me to work around this, but it seems not.

Is there a way to work around this?

like image 687
Nicola Worthington Avatar asked Oct 27 '25 06:10

Nicola Worthington


1 Answers

$@, $* are special variables so should always be defined it's a bug

https://unix.stackexchange.com/questions/16560/bash-su-unbound-variable-with-set-u

a workaround, maybe:

set +u
args=("$@")
set -u

main "${args[@]}"

or maybe also

main "${@:+$@}"
like image 126
Nahuel Fouilleul Avatar answered Oct 28 '25 20:10

Nahuel Fouilleul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!