Tuesday, January 30, 2024

[SOLVED] Bash: Loop over an associative array with list as values

Issue

I am a newbie with Bash. I am trying to loop over the following array -

declare -A X=(
  ['s1']="firstname"
  ['s1'] "secondname"
  ['s2']="surname"
  ['s3']="other"
)

for arg in "${!X[@]}"; do

  echo "${arg}, ${X[${arg}]}"

done

However, I realized that since the key s1 is repeated, only one of the values will be printed. Therefore I did this -

declare -A X=(
  ['s1']="firstname" "secondname"
  ['s2']="surname"
  ['s3']="other"
)

However, I don't know how to loop over it.

The output I am looking for is -

s1, firstname
s1, secondname
s2, surname
s3, other

Please let me know if any clarification is required.


Solution

bash doesn't have 2-dimensional arrays. You coul use space-separated values and nested loops.

declare -A X=(
  ['s1']="firstname secondname"
  ['s2']="surname"
  ['s3']="other"
)

for arg in "${!X[@]}"; do
    for val in ${X[${arg}]}; do
        echo "${arg}, ${val}"
    done
done

Note that this comes with some caveats:

  • It won't work if the nested values can contain whitespace (although you could use a different delimiter that doesn't appear in the values).
  • The values shouldn't contain wildcard characters, since filename expansion occurs when the value is substituted. We can't quote ${X[${arg}]} because that would prevent word splitting.


Answered By - Barmar
Answer Checked By - Cary Denson (WPSolving Admin)