Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash: Loop over an associative array with list as values

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading