36

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...

1 Answer 1

48

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

7
  • 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! Sep 23, 2013 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, 2013 at 16:33
  • Note that ${!var[index]} doesn't work, only ${!var[@]} or ${!var[*]} do :(
    – i336_
    Jun 24, 2016 at 3:09
  • @i336_ - take the ! out so it's ${var[index]}. tldp.org/LDP/abs/html/arrays.html
    – slm
    Jun 24, 2016 at 3: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, 2016 at 3:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.