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

Aru*_*lam 66 arrays bash shell

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

gho*_*g74 76

$ a=(1 2 3 4)
$ echo ${#a[@]}
4
Run Code Online (Sandbox Code Playgroud)

  • @PraveenPremaratne 我在 bash 2.00.0(2)(我可以编译的最旧版本。这是 1996 年的版本!)和 bash 3.2.57(1)(macOS 上使用的版本)中测试了 `${#a[@]}` )。该命令在两个版本中都按预期工作。我想你一定是在其他地方犯了错误。 (5认同)
  • @AhmedAkhtar [这里]有一个不错的解释(/sf/answers/234876281/)。基本上,“ [*]”和“ [@]”都将“数组”分解为带符号的字符串,但是“ [@]”可以在标记中保留空格。但是,当*计数*元素时,它似乎无关紧要;`arr =(foo“ bar baz”); echo $ {arr [*]}`打印`2`,而不是`3`。 (3认同)
  • “ @”在这里做什么? (2认同)

unw*_*ind 18

假设bash:

~> declare -a foo
~> foo[0]="foo"
~> foo[1]="bar"
~> foo[2]="baz"
~> echo ${#foo[*]}
3
Run Code Online (Sandbox Code Playgroud)

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

  • 什么是`*`?它与`@`有什么不同? (2认同)

cod*_*ter 17

从Bash 手册:

$ {#参数}

参数展开值的字符长度被替换.如果参数是' '或'@',则替换的值是位置参数的数量.如果parameter是由' '或'@' 下标的数组名,则替换的值是数组中元素的数量.如果参数是由负数下标的索引数组名称,则该数字被解释为相对于大于参数的最大索引的数字,因此负数索引从数组的末尾开始计数,索引-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
Run Code Online (Sandbox Code Playgroud)

输出:

string length is: 10
array length is: 10
array length is: 10
hash length is: 3
hash length is: 3
Run Code Online (Sandbox Code Playgroud)

处理$@参数数组:

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

输出:

number of args is: 3
number of args is: 3
args_copy length is: 3
Run Code Online (Sandbox Code Playgroud)


小智 7

在tcsh或csh中:

~> set a = ( 1 2 3 4 5 )
~> echo $#a
5
Run Code Online (Sandbox Code Playgroud)


har*_*arm 5

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

$ set a 1 2 3 4
$ count $a
4
Run Code Online (Sandbox Code Playgroud)

  • @codeforester这是一个shell命令,显然可以在Fish shell中使用。操作系统并不重要。 (3认同)

Man*_*Ali 5

这对我来说效果很好:

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