如何在 shell 中查找数组的长度?

如何在 shell 中找到数组的长度?

例如:

arr=(1 2 3 4 5)

我想得到它的长度,在这个例子中是5。

173897 次浏览

假设 Bash:

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

因此,${#ARRAY[*]}扩展到数组 ARRAY的长度。

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

对于那些仍在寻找将数组长度放入变量的方法的人:

foo=$(echo ${'ARRAY[*]}

在 tcsh 或 csh 中:

~> set a = ( 1 2 3 4 5 )
~> echo $#a
5

鱼壳中,数组的长度可以通过以下方式找到:

$ set a 1 2 3 4
$ count $a
4

这对我很有效:

arglen=$#
argparam=$*
if [ $arglen -eq '3' ];
then
echo Valid Number of arguments
echo "Arguments are $*"
else
echo only four arguments are allowed
fi

来自 Bash 手动操作:

${ # 参数}

参数展开值的字符长度被替换。如果参数是‘ < em >’或‘@’,则取代的值是 位置参数的个数。如果参数是数组名 由‘ ’或‘@’订阅,取代的值是 元素。如果参数是索引数组名称 下标为负数时,该数字被解释为 相对于一个大于参数的最大索引,因此 负索引从数组末尾返回,并且 -1引用最后一个元素。

字符串、数组和关联数组的长度

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

产出:

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

处理参数数组 $@:

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

产出:

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