Bash , 调用值时使用变量作为关联数组的名称

Bash , use variable as name of associative array when calling value

这个问题 做的事情与我需要的类似,但是是针对数组的。我是 bash 脚本编写的新手,我需要做的是这样的事情:

# 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 错误。

使用间接引用执行此操作的一种方法是:

ref=$humantocheck[records_file]
echo ${!ref}

Bash: Indirect Expansion Exploration 是间接访问 Bash.

中变量的极好参考

请注意,旨在对原始代码进行最小修改的 echo 命令在几个方面是不安全的。一个安全的替代方案是:

printf '%s\n' "${!ref}"

Why is printf better than echo?

这正是 bash 4.3 功能名称变量(借用自 ksh93)旨在解决的场景。 Namevars 允许 分配 ,而不是单独查找,因此比 ${!foo} 语法更灵活。

# input
humantocheck="human1"

declare -A human1=( ["records_file"]="xxxxx.txt" )
declare -A human2=( ["records_file"]="yyyyy.txt" )

declare -n human=$humantocheck # make human an alias for, in this case, human1
echo "${human[records_file]}"  # use that alias
unset -n human                 # discard that alias

有关关联数组和一般间接扩展的全面讨论,请参阅 BashFAQ #6