bash bash中通过关联数组的foreach循环只返回最后一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16688604/
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
foreach loop through associative array in bash only returns last element
提问by mles
This should print the whole associative array to the console:
这应该将整个关联数组打印到控制台:
#!/bin/sh
declare -a array=([key1]='value1' [key2]='value2')
for key in ${!array[@]}; do
echo "Key = $key"
echo "Value = ${array[$key]}"
done
echo ${array[key1]}
echo ${array[key2]}
Instead it prints oly the last variable:
相反,它只打印最后一个变量:
[mles@sagnix etl-i_test]$ ./test.sh
Key = 0
Value = value2
value2
value2
Where is my fault?
我的错在哪里?
@htor: Bash Version is 3.2.25(1)-release.
@htor:Bash 版本是 3.2.25(1)-release。
回答by
Associative arrays are supported in Bash 4 and newer versions. An array declared with the -aoption is just a regular array that can be indexed by integers, not keys. This declaration results in the array with one element value2. When iterating over the keys with for key in ${!array[@]}the value of $keyis 0and therefore you get the first element.
Bash 4 和更新版本支持关联数组。使用该-a选项声明的数组只是一个可以由整数而不是键索引的常规数组。此声明导致数组具有一个元素value2。当迭代具有isfor key in ${!array[@]}值的键时,您将获得第一个元素。$key0
Given the error output you get when trying to use -Ato declare to array, I assume your Bash version is older than 4. Inspect the variable $BASH_VERSION.
鉴于您在尝试用于-A声明数组时得到的错误输出,我假设您的 Bash 版本早于 4。检查变量$BASH_VERSION。
For a deeper explaination of arrays, see http://mywiki.wooledge.org/BashGuide/Arrays.
有关数组的更深入解释,请参阅http://mywiki.wooledge.org/BashGuide/Arrays。
回答by Ahmed Masud
#!/bin/bash
declare -A array=([key1]='value1' [key2]='value2')
for key in ${!array[@]}; do
echo "array[$key] = ${array[$key]}"
done
echo ${array[key1]}
echo ${array[key2]}

