Home > Back-end >  shell script: Not able to update the values for key
shell script: Not able to update the values for key

Time:04-10

I'm trying to create dictionary at runtime & update the values when same key are found. For some reason not able to append the list or updates the values for the key.

Code

    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"]}

OutPut

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

It always prints the last element appended tot he list. Instead of printing "a new"

The expected output to be.

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

CodePudding user response:

The space before = and = are syntax errors. White space matters for readability. You are trying to use an indexed array (declare -a list) that are referenced using integers, yet you use it as an associate array (declare -A list) that allow reference by arbitrary strings. Also your input data doesn't match your expected output (there is no d in the first section for example). Last line refers to a non-existing variable so removed it.

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 

will give the following output:

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

If you need an associate array and the keys ordered you have two options:

  1. sort the keys before you iterate over them in the loop
  2. explicitly store order of keys in an indexed array, iterate over that to find keys in order. Then lookup the value by key in the associated array.
  • Related