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

Loop through map keys in one line in bash

In python, I can do this in one line:

>>> for key, value in dict(j=1, k=2).items():
...     print(key, value)
...
j 1
k 2
>>>

In bash, I can do this:

$ map=([j]=1 [k]=2); for key in ${!map[@]}; do value=${map[$key]}; echo $key $value; done
j 1
k 2
$

Is there a way in bash to "inline" map declaration into for – similarly how it’s possible in the python example – instead of declaring it beforehand?

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 reason I’m looking for this is to avoid having to declare two additional variables map and value separately – in other words, to make this shorter if possible when doing one-liners on the command line.

>Solution :

There’s no way around doing

declare -A map=([j]=1 [k]=2)

The "${!map[@]}" parameter expansion requires a declared parameter.

Actually, not true. The parameter expansion happily expands an unset variable into the empty string.


You can drop the value variable

for key in "${!map[@]}"; do
  printf '%s %s\n' "$key" "${map[$key]}"
done

Note that associative arrays are unordered. My output for that loop is

k 2
j 1

If you are just looking for a quick way to inspect the contents of a variable, use declare -p

declare -A map=([j]=1 [k]=2)
declare -p map

outputs

declare -A map=([k]="2" [j]="1" )
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