25

Is there a way to get size of associative array in bash:

declare -A array

...without iterating through the elements?

The size of interest is both: just number of elements, and memory amount it consumes?

OzrenTkalcecKrznaric
  • 5,535
  • 4
  • 34
  • 57
wick
  • 1,995
  • 2
  • 20
  • 31

2 Answers2

35

${#array[@]} would return you the size of the array.

$ declare -A array
$ array[foo]='something'
$ array[bar]='blah'
$ array[42]='nothing'
$ echo ${#array[@]}
3
devnull
  • 118,548
  • 33
  • 236
  • 227
  • oh right, totally forgot, thank you. Any idea on resource consumption when the array becomes of substantial size? – wick Aug 12 '13 at 12:01
  • 1
    @wick I don't think that you can determine the resource consumption, though. Consider an alternate approach if your arrays are becoming really *huge*. – devnull Aug 12 '13 at 12:03
  • 1
    Reference: http://www.tldp.org/LDP/abs/html/parameter-substitution.html (scroll down to *Variable length / Substring removal*). – Ohad Schneider Jan 12 '17 at 11:56
14

You can use ${#array[@]} to get the number of elements.

I don't think it is possible to get the amount of memory it consumes however.

paul
  • 1,212
  • 11
  • 15