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.
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.
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.
$ 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.
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
$@
, 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
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