In any case, you can workaround expanding empty arrays throwing unbound by using the ${var+alter} expansion
echo "${arr+${arr[@]}}" The problem with "${arr[@]}" only exists on bash 3 and before, since bash 4
4.4 fixed it: $ bash --version
GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
$ declare -A arr
$ set -u
$ "${arr[@]}"
-bash: arr[@]: unbound variablemacOS is the only one out there missing on this. The other big feature that was only added after bash 3 and is missing on mac is associative arrays
GPL3, buddy. You can use brew to install a newer version and somewhat hide the old one.
Any particular reason why in the shebang instead of set -u?
> The only exception I typically run across is expansion of arrays using "${arr[@]}" syntax
In Bash? Works for me. Edit: another comment mentions it as well. Seem to behave better in newer versions of Bash and only problematic in <= 4.3 https://news.ycombinator.com/item?id=38397241
$ bash -uc 'unset x; echo "=> ${x[@]}"'
=>
$ bash -uc 'x=(); echo "=> ${x[@]}"'
=>
$ bash -uc 'x=(); echo "=> ${x[0]}"'
bash: x[0]: unbound variable
Zsh does not like the first example but both should support: $ bash -uc 'unset x; echo "=> ${x[@]:-null}"'
=> null
> Also handy is `-e` (errexit),It is unfortunately very confusion with functions. Made me like it less over the years.
The clarifications on `-u` and arrays are useful. I'm definitely used to assuming newer (... non-ancient?) versions of Bash are what is available.
"trap" is a great scripting feature that doesn't get talked about enough, IME.
Using `set` (e.g. `set -euo pipefail` as the first line after the shebang) is a common suggestion due to this, and similarly it helps with the `#!/usr/bin/env bash` case where the shebang can't handle additional arguments :-)
- It's almost always preferable to put `-u` (nounset) in your shebang to cause using undeclared variables to be an error. The only exception I typically run across is expansion of arrays using "${arr[@]}" syntax -- if the array is empty, this is considered unbound.
- You can use `-n` (noexec) as a poor-man's attempt at a dry-run, as this will prevent execution of commands.
- Also handy is `-e` (errexit), but you must take care to observe that essentially, this only causes "naked" commands that fail to cause an exit. Personally, I prefer to avoid this and append `|| fail "..."` to commands liberally.