arrays – bash中的关联数组名称数组
我正在尝试使用bash中的数组来管理关联数组列表,而我似乎无法找到哪些不正确.
我正在做的事情: array=(a b c d) for i in ${array[@]}; do declare -A $i done a[key]=avalue b[key]=bvalue c[key]=cvalue d[key]=dvalue 这一切似乎工作正常,因为我可以通过引用${a [key]}手动返回值就好了. 但是,当我试图迭代使用数组变量时,它并没有真正给我我所期望的. for index in ${array[@]}; do echo ${index[key]} done 回来就像我要跑的一样 for index in ${array[@]}; do echo $index done 我觉得我错过了一些简单的东西,但寻找答案并没有找到任何解决方案.任何援助将不胜感激. 解决方法
这是一个解决方案,使用shell间接.这适用于任何支持关联数组的bash.间接必须包含整个引用,包括下标,这有点尴尬.
for index in "${array[@]}"; do indexkey=${index}[key] echo "${!indexkey}" done 使用现代bash(至少v4.3),您可以使用nameref声明来创建别名.这样更方便,因为您可以使用具有相同别名的不同键: for index in "${array[@]}"; do declare -n subarray=$index echo "${subarray[key]}" done 接近解释的东西. 正如Etan Reisner在评论中指出的那样,这个问题在Bash FAQ entry中有一定篇幅.但是,在我写的那一天,FAQ条目包括免责声明“检修此页面需要一些时间和工作”,并且确实,FAQ条目目前并不像人们所希望的那样清晰.所以这是我的简短摘要: > declare(和其他相关的内置函数,包括export,local和typeset)评估它们的参数.因此,您可以在declare语句中构建变量名称. my_array[${place}:${feature}] 只要${place}没有值包含冒号(当然,您可以使用不同的字符而不是冒号),将会工作. declare -A assoc declare -a indexed key=42 # This assigns the element whose key is "key" assoc[key]=foo # This assigns the element whose key is 42 indexed[key]=foo # If $key had not been defined,the above would have assigned # the element whose key was 0,without an error message (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |