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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4423306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:57:21  来源:igfitidea点击:

How do I find the number of arguments passed to a Bash script?

basharguments

提问by sabri

How do I find the number of arguments passed to a Bash script?

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

This is what I have currently:

这是我目前所拥有的:

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

Are there other (better) ways of doing this?

是否有其他(更好的)方法可以做到这一点?

回答by zsalzbank

The number of arguments is $#

参数的数量是 $#

Search for it on this page to learn more: http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST

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

回答by Paused until further notice.

#!/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"

回答by Michael Brux

to add the original reference:

添加原始参考:

You can get the number of arguments from the special parameter $#. Value of 0 means "no arguments". $#is read-only.

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

When used in conjunction with shiftfor argument processing, the special parameter $#is decremented each time Bash Builtin shiftis executed.

当与shiftfor 参数处理结合使用时,$#每次shift执行Bash Builtin 时都会递减特殊参数。

see Bash Reference Manualin section 3.4.2 Special Parameters:

请参阅Bash 参考手册中的3.4.2 特殊参数部分:

  • "The shell treats several parameters specially. These parameters may only be referenced"

  • and in this section for keyword $#"Expands to the number of positional parameters in decimal."

  • “shell 对几个参数进行了特殊处理,这些参数只能被引用

  • 并在本节中为关键字$#“扩展到十进制位置参数的数量”。

回答by VIPIN KUMAR

Below is the easy one -

下面是简单的——

cat countvariable.sh

猫计数变量.sh

echo "$@" |awk '{for(i=0;i<=NF;i++); print i-1 }'

Output :

输出 :

#./countvariable.sh 1 2 3 4 5 6
6
#./countvariable.sh 1 2 3 4 5 6 apple orange
8

回答by Jeff Gaer

that value is contained in the variable $#

该值包含在变量中 $#