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?
Bash, however, includes the ability to create associative arrays, and it treats these arrays the same as any other array. An associative array lets you create lists of key and value pairs, instead of just numbered values. You can assign values to arbitrary keys: $ declare -A userdata.
There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously.
An associative array in bash is declared by using the declare -A command (How surprising, I know :D). The variable inside the brackets - [] will be the KEY and the value after the equal sign will be the VALUE.
Bash supports one-dimensional numerically indexed and associative arrays types. Numerical arrays are referenced using integers, and associative are referenced using strings. Numerically indexed arrays can be accessed from the end using negative indices, the index of -1 references the last element.
${#array[@]}
would return you the size of the array.
$ declare -A array $ array[foo]='something' $ array[bar]='blah' $ array[42]='nothing' $ echo ${#array[@]} 3
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With