【问题标题】:Shell - How to declare an associative array and iterate through [duplicate]Shell - 如何声明关联数组并遍历[重复]
【发布时间】:2020-11-14 02:58:33
【问题描述】:

我正在尝试在 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

知道我做错了什么吗?

【问题讨论】:

  • 感谢@FredrikPihl,使用 Paused 提出的解决方案,直到另行通知,我得到了相同的结果,只有最后一个数组值显示在键 0 处。
  • 您是否将test_array 声明为关联数组? declare -A test_array
  • 您的意思是 Posix sh?我不知道shell是哪个程序。
  • @kvantour,刚刚试过,还是一样。请注意,我在 sh,而不是 bash。

标签: arrays shell for-loop


【解决方案1】:

我在 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

【讨论】:

  • 这没有回答问题。问题是关于 Posix sh,它没有 declare 语句,也不支持关联数组
  • 他没有在问题中指定posix sh。我回答后澄清了这一点。
【解决方案2】:

关联数组是bash 4 的功能!在sh 中不可用。

正如 kvantour 在 cmets 中指出的,我们可以模仿 sh 中关联数组的行为。看到这个reference1reference2

【讨论】:

    猜你喜欢
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 2021-11-05
    • 2013-11-03
    • 2020-08-06
    • 1970-01-01
    相关资源
    最近更新 更多