如何在 Bash 中迭代关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3112687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to iterate over associative arrays in Bash
提问by pex
Based on an associative array in a Bash script, I need to iterate over it to get the key and value.
基于 Bash 脚本中的关联数组,我需要对其进行迭代以获取键和值。
#!/bin/bash
declare -A array
array[foo]=bar
array[bar]=foo
I actually don't understand how to get the key while using a for-in loop.
我实际上不明白如何在使用 for-in 循环时获取密钥。
回答by Paused until further notice.
The keys are accessed using an exclamation point: ${!array[@]}
, the valuesare accessed using ${array[@]}
.
使用感叹号访问键:${!array[@]}
,使用 访问值${array[@]}
。
You can iterate over the key/value pairs like this:
您可以像这样迭代键/值对:
for i in "${!array[@]}"
do
echo "key : $i"
echo "value: ${array[$i]}"
done
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.
请注意在for
语句中使用引号将变量括起来(加上使用@
代替*
)。这是必要的,以防任何键包含空格。
The confusion in the other answer comes from the fact that your question includes "foo" and "bar" for both the keys andthe values.
另一个答案中的混淆来自这样一个事实,即您的问题包括键和值的“foo”和“bar” 。
回答by tonio
You can access the keys with ${!array[@]}
:
您可以通过以下方式访问密钥${!array[@]}
:
bash-4.0$ echo "${!array[@]}"
foo bar
Then, iterating over the key/value pairs is easy:
然后,迭代键/值对很容易:
for i in "${!array[@]}"
do
echo "key :" $i
echo "value:" ${array[$i]}
done
回答by coderofsalvation
Use this higher order function to prevent the pyramid of doom
使用这个高阶函数来防止厄运金字塔
foreach(){
arr="$(declare -p )" ; eval "declare -A f="${arr#*=};
for i in ${!f[@]}; do "$i" "${f[$i]}"; done
}
example:
例子:
$ bar(){ echo " -> "; }
$ declare -A foo["flap"]="three four" foo["flop"]="one two"
$ foreach foo bar
flap -> three four
flop -> one two
回答by EJISRHA
declare -a arr
echo "-------------------------------------"
echo "Here another example with arr numeric"
echo "-------------------------------------"
arr=( 10 200 3000 40000 500000 60 700 8000 90000 100000 )
echo -e "\n Elements in arr are:\n ${arr[0]} \n ${arr[1]} \n ${arr[2]} \n ${arr[3]} \n ${arr[4]} \n ${arr[5]} \n ${arr[6]} \n ${arr[7]} \n ${arr[8]} \n ${arr[9]}"
echo -e " \n Total elements in arr are : ${arr[*]} \n"
echo -e " \n Total lenght of arr is : ${#arr[@]} \n"
for (( i=0; i<10; i++ ))
do echo "The value in position $i for arr is [ ${arr[i]} ]"
done
for (( j=0; j<10; j++ ))
do echo "The length in element $j is ${#arr[j]}"
done
for z in "${!arr[@]}"
do echo "The key ID is $z"
done
~