虽然建议的解决方案使用“set -u”进行 Bash 空数组扩展 https://stackoverflow.com/questions/7577052/bash-empty-array-expansion-with-set-u对我来说效果很好,事实证明数组处理在最近发布的 (2016/09/16) bash 4.4 中发生了变化(例如,在 Debian Stretch 中可用)。
$ bash --version | head -n1
bash --version | head -n1
GNU bash, version 4.4.0(1)-release (x86_64-pc-linux-gnu)
现在空数组扩展不会发出警告
$ set -u
$ arr=()
$ echo "${arr[@]}"
$ # everything is fine
相关问题中提出的解决方案在 bash-4.4 中失败:
$ set -u
$ arr2=()
$ arr2=( ${arr2[@] + "${arr2[@]}"} 'foo' )
bash: ${arr2[@] + "$arr2[@]"}: bad substitution
有没有人得到关于(或多或少)版本无关解决方案的建议,而无需对数组长度或 bash 版本进行额外检查?
我仍在亲自调查最新的 bash 更改
EDIT
由于我最初的问题似乎有些令人困惑,这里澄清了我试图实现的目标。
测试脚本:
#!/usr/bin/env bash
set -euo pipefail
bash --version | head -n1
arr=()
# some external environment variables are set / command line arguments passed to script
if test -n "${USE_EXTRA_ARGUMENT_1-}" ; then
arr=( ${arr[@] + "${arr[@]}"} 'foo' )
fi
if test -n "${USE_EXTRA_ARGUMENT_2-}" ; then
arr=( ${arr[@] + "${arr[@]}"} 'bar' )
fi
# just a dummy command
echo "${arr[@]-}"
Bash 4.3(Arch linux)运行:
$ USE_EXTRA_ARGUMENT_1=baz bash xxx.sh
GNU bash, version 4.3.46(1)-release (x86_64-unknown-linux-gnu)
foo
Bash 4.4(Debian 延伸版)运行:
$ USE_EXTRA_ARGUMENT_1=baz bash xxx.sh
GNU bash, version 4.4.0(1)-release (x86_64-pc-linux-gnu)
xxx.sh: line 9: ${arr[@] + "${arr[@]}"}: bad substitution
或者我在使用 bash 数组时犯了严重错误?