我试图在sh中声明一个关联数组,并通过for循环运行:
test_array=([a]=10 [b]=20 [c]=30)
for k in "${!test_array[@]}"
do
printf "%s\n" "$k=${test_array[$k]}"
done
这只会返回最后一个数组元素:
0=30
知道我在做什么错吗?
答案 0 :(得分:0)
我在bash中对此进行了测试。
比较这两个功能。在第一个中,我创建一个带有整数索引的数组,第二个中,创建一个关联数组。我得到了bash预期的结果。我不确定您使用的是哪个Shell变体,所以我不知道您是否需要添加声明或引用数组键,还是两者都需要。
x ()
{
declare -a test_array;
test_array=([a]=10 [b]=20 [c]=30);
for k in "${!test_array[@]}";
do
printf "%s\n";
echo "$k=${test_array[$k]}";
done
}
y
y ()
{
declare -A test_array;
test_array=(["a"]=10 ["b"]=20 ["c"]=30);
for k in "${!test_array[@]}";
do
printf "%s\n";
echo "$k=${test_array[$k]}";
done
}
x
答案 1 :(得分:0)
关联数组是bash 4
的功能!在sh
中不可用。
正如 kvantour 在评论中指出的那样,我们可以模仿sh中关联数组的行为。参见此reference1,reference2。