Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash associative array size

Tags:

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?

like image 232
wick Avatar asked Aug 12 '13 11:08

wick


People also ask

What is an associative array in bash?

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.

How big can a bash array be?

There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously.

What is the command to create an associative array in bash?

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.

How many dimensions do bash arrays have?

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.


2 Answers

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

$ declare -A array $ array[foo]='something' $ array[bar]='blah' $ array[42]='nothing' $ echo ${#array[@]} 3 
like image 181
devnull Avatar answered Nov 09 '22 11:11

devnull


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.

like image 36
paul Avatar answered Nov 09 '22 12:11

paul