如何在shell中求数组的长度?

jq6vz3qz  于 2023-02-05  发布在  Shell
关注(0)|答案(7)|浏览(182)

如何在shell中计算数组的长度?
例如:

arr=(1 2 3 4 5)

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

6rvt4ljy

6rvt4ljy1#

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

0mkxixxg2#

来自巴什manual
${#参数}
将替换形参的扩展值的字符长度。如果形参是""或"@",则替换的值是位置形参的数目。如果形参是下标为""或"@"的数组名称,则替换的值是数组中的元素数目。如果形参是下标为负数的索引数组名称,该数字被解释为相对于大于参数的最大索引的1,因此负索引从数组末尾开始往回计数,索引-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
xv8emn3q

xv8emn3q3#

假设猛击:

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

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

a5g8bdjr

a5g8bdjr4#

在tcsh或csh中:

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

xtfmy6hx5#

Fish Shell中,数组的长度可通过下式求出:

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

x6h2sr286#

这对我来说很有效:

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

xzabzqsa7#

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

foo="${#ARRAY[*]}"

相关问题