Bash – is there a way to list all ‘indexes IDs’ (keys) on a bash associative array variable

arraybash

I have this array:

declare -A astr

I add elements to it:

astr[elemA]=123
astr[elemB]=199

But later on I need to know what are the indexes IDs (elemA and elemB) and list them.

echo "${astr[@]}" #this only get me the values...

Best Answer

You can get the list of "keys" for the associative array like so:

$ echo "${!astr[@]}"
elemB elemA

You can iterate over the "keys" like so:

for i in "${!astr[@]}"
do   
  echo "key  : $i"
  echo "value: ${astr[$i]}"
done

Example

$ for i in "${!astr[@]}"; do echo "key  : $i"; echo "value: ${astr[$i]}"; done
key  : elemB
value: 199
key  : elemA
value: 123

References

Related Question