How to find the length of an array in shell? How to find the length of an array in shell? arrays arrays

How to find the length of an array in shell?


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


From Bash manual:

${#parameter}

The length in characters of the expanded value of parameter is substituted. If parameter is ‘’ or ‘@’, the value substituted is the number of positional parameters. If parameter is an array name subscripted by ‘’ or ‘@’, the value substituted is the number of elements in the array. If parameter is an indexed array name subscripted by a negative number, that number is interpreted as relative to one greater than the maximum index of parameter, so negative indices count back from the end of the array, and an index of -1 references the last element.

Length of strings, arrays, and associative arrays

string="0123456789"                   # create a string of 10 charactersarray=(0 1 2 3 4 5 6 7 8 9)           # create an indexed array of 10 elementsdeclare -A hashhash=([one]=1 [two]=2 [three]=3)      # create an associative array of 3 elementsecho "string length is: ${#string}"   # length of stringecho "array length is: ${#array[@]}"  # length of array using @ as the indexecho "array length is: ${#array[*]}"  # length of array using * as the indexecho "hash length is: ${#hash[@]}"    # length of array using @ as the indexecho "hash length is: ${#hash[*]}"    # length of array using * as the index

output:

string length is: 10array length is: 10array length is: 10hash length is: 3hash length is: 3

Dealing with $@, the argument array:

set arg1 arg2 "arg 3"args_copy=("$@")echo "number of args is: $#"echo "number of args is: ${#@}"echo "args_copy length is: ${#args_copy[@]}"

output:

number of args is: 3number of args is: 3args_copy length is: 3


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.