shell 脚本:无法更新键的值

shell script: Not able to update the values for key

我正在尝试在运行时创建字典并在找到相同键时更新值。由于某种原因无法附加列表或更新键的值。

代码

    declare -a list
    
     list+=(["key1"]="a")
     list+=(["key4"]="b")
     list+=(["key2"]="c")
     list+=(["key3"]="b")
    
    
     list=("${list["key1"]}" "new")
     list=("${list["key2"]}" "xyz")
     list=("${list["key3"]}" "mno")
     list=("${list["key4"]}" "klo")
      
for i in "${list[@]}"  
 do  
 echo The key value of element "${list[$i]}" is "$i"  
done 

echo ${arr["key1"]}

输出

The key value of element b is b
The key value of element b is klo
b 

它总是打印附加到列表中的最后一个元素。而不是打印 "a new"

预期输出为。

The key value of element key1 is a new
The key value of element key2 is b xyz
The key value of element key3 is c mno
The key value of element key4 is d klo

+==之前的space是语法错误。白色 space 对可读性很重要。您正在尝试使用使用整数引用的索引数组 (declare -a list),但您将其用作允许通过任意字符串引用的关联数组 (declare -A list)。此外,您的输入数据与您的预期输出不匹配(例如,第一部分中没有 d )。最后一行引用了一个 non-existing 变量,因此将其删除。

declare -A list
    
list[key1]="a"
list[key2]="b"
list[key3]="c"
list[key4]="d"

list[key1]="${list[key1]} new"
list[key2]="${list[key2]} xyz"
list[key3]="${list[key3]} mno"
list[key4]="${list[key4]} klo"

for i in "${!list[@]}"  
do  
    echo The key value of element "$i" is "${list[$i]}"
done 

将给出以下输出:

The key value of element key4 is d klo
The key value of element key2 is b xyz
The key value of element key3 is c mno
The key value of element key1 is a new

如果您需要关联数组和排序的键,您有两个选择:

  1. 在循环中迭代之前对键进行排序
  2. 在索引数组中显式存储键的顺序,迭代 在那之上按顺序找到钥匙。然后通过键入查找值 关联的数组。