Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the length of an array in shell?

Tags:

arrays

bash

shell

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.

like image 753
Arunachalam Avatar asked Dec 11 '09 07:12

Arunachalam


People also ask

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

To get the length of an array, we can use the {#array[@]} syntax in bash. The # in the above syntax calculates the array size, without hash # it just returns all elements in the array.

What is array length ()?

length is a property of arrays in JavaScript that returns or sets the number of elements in a given array. The length property of an array can be returned like so. let desserts = ["Cake", "Pie", "Brownies"]; console. log(desserts.


2 Answers

$ a=(1 2 3 4) $ echo ${#a[@]} 4 
like image 106
ghostdog74 Avatar answered Sep 30 '22 23:09

ghostdog74


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 characters array=(0 1 2 3 4 5 6 7 8 9)           # create an indexed array of 10 elements declare -A hash hash=([one]=1 [two]=2 [three]=3)      # create an associative array of 3 elements echo "string length is: ${#string}"   # length of string echo "array length is: ${#array[@]}"  # length of array using @ as the index echo "array length is: ${#array[*]}"  # length of array using * as the index echo "hash length is: ${#hash[@]}"    # length of array using @ as the index echo "hash length is: ${#hash[*]}"    # length of array using * as the index 

output:

string length is: 10 array length is: 10 array length is: 10 hash length is: 3 hash 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: 3 number of args is: 3 args_copy length is: 3 
like image 42
codeforester Avatar answered Sep 30 '22 22:09

codeforester