如何在 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[@]}
,values 使用 ${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屋!