Search code examples
bashassociative-array

Bash how to parse asscoiative array from argument?


I am trying to read a string into an associative array.

The string is being properly escaped and read into .sh file:

./myScript.sh "[\"el1\"]=\"val1\" [\"el2\"]=\"val2\""

within the script

#!/bin/bash -e
declare -A myArr=( "${1}" ) #it doesn't work either with or without quotes

All I get is:

line 2: myArr: "${1}": must use subscript when assigning associative array

Googling the error only results in "your array is not properly formatted" results.


Solution

  • solution:

    ./test.sh "( [\"el1\"]=\"val1\" [\"el2\"]=\"val2\" )"
    

    and within the script:

    #!/bin/bash -e
    
    declare -A myArr="${1}"
    declare -p myArr
    
    for i in "${!myArr[@]}"
    do
      echo "key  : $i"
      echo "value: ${myArr[$i]}"
    done
    

    Returns:

    > ./test.sh "( [\"el1\"]=\"val1\" [\"el2\"]=\"val2\" )"
    declare -A myArr=([el2]="val2" [el1]="val1" )
    key  : el2
    value: val2
    key  : el1
    value: val1
    

    I can't explain why this works, or why the order changes though.

    Test it yourself here