如何在Bash中迭代关联数组 [英] How to iterate over associative arrays in Bash
问题描述
基于Bash脚本中的关联数组,我需要对其进行迭代以获取键和值.
Based on an associative array in a Bash script, I need to iterate over it to get the key and value.
#!/bin/bash
declare -A array
array[foo]=bar
array[bar]=foo
我实际上不了解在使用for-in循环时如何获取密钥.
I actually don't understand how to get the key while using a for-in loop.
推荐答案
使用惊叹号访问键:${!array[@]}
,使用${array[@]}
.
The keys are accessed using an exclamation point: ${!array[@]}
, the values are accessed using ${array[@]}
.
您可以像这样遍历键/值对:
You can iterate over the key/value pairs like this:
for i in "${!array[@]}"
do
echo "key : $i"
echo "value: ${array[$i]}"
done
请注意在for
语句中的变量周围使用引号(加上@
而不是*
).如果任何键包含空格,则这是必需的.
Note the use of quotes around the variable in the for
statement (plus the use of @
instead of *
). This is necessary in case any keys include spaces.
另一个答案的混乱来自于这样一个事实,即您的问题包括键和的值"foo"和"bar".
The confusion in the other answer comes from the fact that your question includes "foo" and "bar" for both the keys and the values.
这篇关于如何在Bash中迭代关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!