bash脚本编程 - 通过迭代"变"关联数组列表变量名 [英] Bash scripting - Iterating through "variable" variable names for a list of associative arrays
问题描述
我已经得到了我想要遍历并检索其键/值对关联数组变量列表。
I've got a variable list of associative arrays that I want to iterate through and retrieve their key/value pairs.
我通过列出它的所有按键和获取的值,即一个关联数组进行迭代。
I iterate through a single associative array by listing all its keys and getting the values, ie.
for key in "${!queue1[@]}" do
echo "key : $key"
echo "value : ${queue1[$key]}"
done
棘手的部分是,关联数组的名称都是可变的变量,例如鉴于数= 5,关联数组将被命名为队列1,队列2,队列3,队列4,队列5。
The tricky part is that the names of the associative arrays are variable variables, e.g. given count = 5, the associative arrays would be named queue1, queue2, queue3, queue4, queue5.
我试图取代基于计数上面的顺序,但到目前为止,括号和eval的每个组合还没有产生更多的再不济替代错误。例如如下:
I'm trying to replace the sequence above based on a count, but so far every combination of parentheses and eval has not yielded much more then bad substitution errors. e.g below:
for count in {1,2,3,4,5} do
for key in "${!queue${count}[@]}" do
echo "key : $key"
echo "value : ${queue${count}[$key]}"
done
done
帮助将非常AP preciated!
Help would be very much appreciated!
推荐答案
的困难在这里从这样的事实,即语法间接扩张( $ {!nameref}
)与语法冲突从一个关联数组提取键( $ {!数组[@]}
)。我们只能有一个或另一个,而不是两个。
The difficulty here stems from the fact that the syntax for indirect expansion (${!nameref}
) clashes with the syntax for extracting keys from an associative arrays (${!array[@]}
). We can have only one or the other, not both.
警惕,因为我关于使用评估
,我不能看到周围用其提取的间接引用关联数组中键的方式:
Wary as I am about using eval
, I cannot see a way around using it to extract the keys of an indirectly referenced associative array:
keyref="queue${count}[@]"
for key in $(eval echo '${!'$keyref'}'); do ... ; done
您可以但是要避免评估
和提取给出的键数组中的值时,使用间接扩展。请注意, [重点]
后缀必须为扩展的一部分:
You can however avoid eval
and use indirect expansion when extracting a value from an array given the key. Do note that the [key]
suffix must be part of the expansion:
valref="queue${count}[$key]"
echo ${!valref}
要放在这一背景下:
for count in {1..5} ; do
keyref="queue${count}[@]"
for key in $(eval echo '${!'$keyref'}'); do
valref="queue${count}[$key]"
echo "key = $key"
echo "value = ${!valref}"
done
done
这篇关于bash脚本编程 - 通过迭代"变"关联数组列表变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!