这个问题 bad substitution shell- trying to use variable as name of array 与我的需求类似,而且是关于数组的。我对bash脚本编程非常陌生,我需要做的事情如下:
预期输出为:
但是当我尝试这样做时,会出现“bad substitution”错误。
# input
humantocheck="human1"
declare -A human1
declare -A human2
human1=( ["records_file"]="xxxxx.txt")
human2=( ["records_file"]="yyyyy.txt")
echo ${$humantocheck[records_file]}
预期输出为:
xxxxx.txt
但是当我尝试这样做时,会出现“bad substitution”错误。
humantocheck
不是一个数组。如果有任何东西可以工作,它将是${${!humantocheck}[records_file]}
的变体,但我并不自信(我没有找到魔术组合)。 (参见shell参数扩展。) - Jonathan Lefflerhuman1
或human2
创建一个通用的关联数组human
,然后引用它。不幸的是,我认为没有一种方法可以一次性地分配整个关联数组。我想到的最好办法是使用循环逐个复制关联数组的元素:for key in "${!human1[@]}"; do human[$key]="${human1[$key]}"; done
。一般来说,使用间接变量名会导致复杂性,并需要重新考虑/重写。 - Jonathan Leffler