How to find the length of an array in shell?

Viewed 164335

How do I find the length of an array in shell?

For example:

arr=(1 2 3 4 5)

And I want to get its length, which is 5 in this case.

7 Answers
$ a=(1 2 3 4)
$ echo ${#a[@]}
4

Assuming bash:

~> declare -a foo
~> foo[0]="foo"
~> foo[1]="bar"
~> foo[2]="baz"
~> echo ${#foo[*]}
3

So, ${#ARRAY[*]} expands to the length of the array ARRAY.

Related