26

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

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

  • 1
    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
  • @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 3:09
  • @i336_ - take the ! out so it's ${var[index]}. tldp.org/LDP/abs/html/arrays.html – slm Jun 24 '16 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 '16 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.