我如何找到传递给Bash脚本的参数的数量?

这是我目前拥有的:

#!/bin/bash
i=0
for var in "$@"
do
  i=i+1
done

还有其他(更好的)方法吗?


当前回答

#!/bin/bash
echo "The number of arguments is: $#"
a=${@}
echo "The total length of all arguments is: ${#a}: "
count=0
for var in "$@"
do
    echo "The length of argument '$var' is: ${#var}"
    (( count++ ))
    (( accum += ${#var} ))
done
echo "The counted number of arguments is: $count"
echo "The accumulated length of all arguments is: $accum"

其他回答

下面是简单的一个

猫countvariable.sh

echo "$@" | awk '{print NF}'

输出:

#./countvariable.sh 1 2 3 4 5 6
6
#./countvariable.sh 1 2 3 4 5 6 apple orange
8
#!/bin/bash
echo "The number of arguments is: $#"
a=${@}
echo "The total length of all arguments is: ${#a}: "
count=0
for var in "$@"
do
    echo "The length of argument '$var' is: ${#var}"
    (( count++ ))
    (( accum += ${#var} ))
done
echo "The counted number of arguments is: $count"
echo "The accumulated length of all arguments is: $accum"

添加原始引用:

您可以从特殊参数$#中获取参数的数量。0表示“无参数”。$#是只读的。

当与shift一起用于参数处理时,特殊参数$#在每次Bash内置shift执行时都会递减。

参见3.4.2特殊参数:

shell对几个参数进行了特殊处理。这些参数只能被引用。 在此部分中,关键字$#“扩展为十进制形式的位置参数的数量。”

参数的数量是$#

在本页搜索以了解更多信息: http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST