40

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...
Aquarius Power
  • 4,099
  • 5
  • 38
  • 56

1 Answers1

51

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

slm
  • 363,520
  • 117
  • 767
  • 871
  • 2
    I just found it also works for numerically indexed arrays also: `astr2=(a b c d e);echo ${!astr2[@]};unset astr2[2];echo ${!astr2[@]}` thx! – Aquarius Power Sep 23 '13 at 16:29
  • 1
    @AquariusPower - Yeah if you roll the edits back on my answer you'll see that i had originally included the numeric index too, but then droped it since you wanted named hashes. – slm Sep 23 '13 at 16:33
  • Note that `${!var[index]}` doesn't work, only `${!var[@]}` or `${!var[*]}` do :( – i336_ Jun 24 '16 at 03:09
  • @i336_ - take the `!` out so it's `${var[index]}`. http://www.tldp.org/LDP/abs/html/arrays.html – slm Jun 24 '16 at 03:14
  • Sorry, clarification: I was trying to determine the associative key for numeric index *n*. I realized I can easily do `keys=(${!var[@]})` and then `${keys[n]}`, giving me the index, but around the same time I also realized I need to rethink my approach. – i336_ Jun 24 '16 at 03:32
  • and, inside functions, the only way I found (when passing an array id as parameter) was to use `declare -n ref="$1"`, and then use ref to do anything you would with the array normally (least `declare -p ref` will differ of course) – Aquarius Power Oct 12 '16 at 04:25
  • Awesome! Thanks. – Scottie H Jan 06 '21 at 23:25