检查传递给 Bash 脚本的参数数量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18568706/
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-10 00:08:37  来源:igfitidea点击:

Check number of arguments passed to a Bash script

bashparameter-passingcommand-line-arguments

提问by Naftaly

I would like my Bash script to print an error message if the required argument count is not met.

如果未满足所需的参数计数,我希望我的 Bash 脚本打印错误消息。

I tried the following code:

我尝试了以下代码:

#!/bin/bash
echo Script name: 
test: line 4: [2: command not found
echo $# arguments if [$# -ne 1]; then echo "illegal number of parameters" fi

For some unknown reason I've got the following error:

由于某些未知原因,我收到以下错误:

if [ "$#" -ne 1 ]; then
    echo "Illegal number of parameters"
fi

What am I doing wrong?

我究竟做错了什么?

回答by konsolebox

Just like any other simple command, [ ... ]or testrequires spaces between its arguments.

就像任何其他简单命令一样,[ ... ]或者test在其参数之间需要空格。

if test "$#" -ne 1; then
    echo "Illegal number of parameters"
fi

Or

或者

[[ $# -ne 1 ]]

Suggestions

建议

When in Bash, prefer using [[ ]]instead as it doesn't do word splitting and pathname expansion to its variables that quoting may not be necessary unless it's part of an expression.

在 Bash 中,更喜欢使用,[[ ]]因为它不会对其变量进行分词和路径名扩展,除非它是表达式的一部分,否则可能不需要引用。

[[ ($# -eq 1 || ($# -eq 2 &&  == <glob pattern>)) &&  =~ <regex pattern> ]]

It also has some other features like unquoted condition grouping, pattern matching (extended pattern matching with extglob) and regex matching.

它还具有一些其他功能,例如不带引号的条件分组、模式匹配(扩展模式匹配extglob)和正则表达式匹配。

The following example checks if arguments are valid. It allows a single argument or two.

以下示例检查参数是否有效。它允许一个或两个参数。

A=1
[[ 'A + 1' -eq 2 ]] && echo true  ## Prints true.

For pure arithmetic expressions, using (( ))to some may still be better, but they are still possible in [[ ]]with its arithmetic operators like -eq, -ne, -lt, -le, -gt, or -geby placing the expression as a single string argument:

对于纯算术表达式,使用(( ))to some 可能仍然更好,但它们仍然可以[[ ]]使用其算术运算符,如-eq, -ne, -lt, -le, -gt,或-ge将表达式作为单个字符串参数:

if [[ $# -ne 1 ]]; then
    echo "Illegal number of parameters"
    exit 2
fi

That should be helpful if you would need to combine it with other features of [[ ]]as well.

如果您还需要将它与其他功能结合起来,那应该会有所帮助[[ ]]

Exiting the script

退出脚本

It's also logical to make the script exit when invalid parameters are passed to it. This has already been suggested in the commentsby ekangasbut someone edited this answer to have it with -1as the returned value, so I might as well do it right.

当向脚本传递无效参数时,让脚本退出也是合乎逻辑的。这已经在ekangas评论中提出了,但有人编辑了这个答案以将其作为返回值,所以我不妨做对。-1

-1though accepted by Bash as an argument to exitis not explicitly documented and is not right to be used as a common suggestion. 64is also the most formal value since it's defined in sysexits.hwith #define EX_USAGE 64 /* command line usage error */. Most tools like lsalso return 2on invalid arguments. I also used to return 2in my scripts but lately I no longer really cared, and simply used 1in all errors. But let's just place 2here since it's most common and probably not OS-specific.

-1尽管被 Bash 接受exit为没有明确记录的论据,并且不适合用作常见建议。 64也是最正式的值,因为它是在sysexits.hwith 中定义的#define EX_USAGE 64 /* command line usage error */。大多数工具ls也会返回2无效参数。我也曾经2在我的脚本中返回,但最近我不再真正关心,只是1在所有错误中使用。但让我们把2它放在这里,因为它是最常见的并且可能不是特定于操作系统的。

if (( $# != 1 )); then
    echo "Illegal number of parameters"
fi

References

参考

回答by Aleks-Daniel Jakimenko-A.

It might be a good idea to use arithmetic expressionsif you're dealing with numbers.

如果您正在处理数字,使用算术表达式可能是个好主意。

if [ "$#" != "1" ]; then

回答by jhvaras

On []: !=, =, == ... are stringcomparison operators and -eq, -gt ... are arithmeticbinary ones.

在 [] 上: !=, =, == ... 是字符串比较运算符, -eq, -gt ... 是算术二进制运算符。

I would use:

我会用:

if [ $# -eq 1 ]; then

Or:

或者:

#!/bin/bash
# usage-message.sh

: ${1?"Usage: 
[ "$#" -ne 1 ] && ( usage && exit 1 ) || main
ARGUMENT"} # Script exits here if command-line parameter absent, #+ with following error message. # usage-message.sh: 1: Usage: usage-message.sh ARGUMENT

回答by Pat

If you're only interested in bailing if a particular argument is missing, Parameter Substitutionis great:

如果您只对缺少特定参数的情况感兴趣,那么参数替换非常棒:

myFunc() {
  if [[ "$#" -gt 0 ]]; then
    for arg in "$@"; do
      echo $arg
    done
  fi
}

myFunc "$@"

回答by Dwight Spencer

A simple one liner that works can be done using:

可以使用以下方法完成一个简单的衬里:

[ "$#" -ne 1 ] && echo "USAGE 
    while getopts "x:c" opt; do
      case $opt in
        c)
          echo "-$opt was triggered, deploy to ci account" >&2
          DEPLOY_CI_ACCT="true"
          ;;
            x)
              echo "-$opt was triggered, Parameter: $OPTARG" >&2 
              CMD_TO_EXEC=${OPTARG}
              ;;
            \?)
              echo "Invalid option: -$OPTARG" >&2 
              Usage
              exit 1
              ;;
            :)
              echo "Option -$OPTARG requires an argument." >&2 
              Usage
              exit 1
              ;;
          esac
        done
<PARAMETER>" && exit

This breaks down to:

这分解为:

  1. test the bash variable for size of parameters $# not equals 1 (our number of sub commands)
  2. if true then call usage() function and exit with status 1
  3. else call main() function
  1. 测试 bash 变量的参数大小 $# 不等于 1(我们的子命令数)
  2. 如果为真,则调用 usage() 函数并以状态 1 退出
  3. 否则调用 main() 函数

Thinks to note:

认为要注意:

  • usage() can just be simple echo "$0: params"
  • main can be one long script
  • usage() 可以只是简单的 echo "$0: params"
  • main 可以是一个长脚本

回答by Nick Hall

Check out thisbash cheatsheet, it can help alot.

查看这个bash 备忘单,它可以提供很多帮助。

To check the length of arguments passed in, you use "$#"

要检查传入的参数的长度,您可以使用 "$#"

To use the array of arguments passed in, you use "$@"

要使用传入的参数数组,您可以使用 "$@"

An example of checking the length, and iterating would be:

检查长度和迭代的示例是:

if [ $# -ne 1 ]; 
    then echo "illegal number of parameters"
fi

This articled helped me, but was missing a few things for me and my situation. Hopefully this helps someone.

这篇文章对我有帮助,但对我和我的情况来说遗漏了一些东西。希望这有助于某人。

回答by panticz

Here a simple one liners to check if only one parameter is given otherwise exit the script:

这里有一个简单的单行代码来检查是否只给出了一个参数,否则退出脚本:

##代码##

回答by IsaacE

In case you want to be on the safe side, I recommend to use getopts.

如果您想安全起见,我建议您使用 getopts。

Here is a small example:

这是一个小例子:

##代码##

see more details here for example http://wiki.bash-hackers.org/howto/getopts_tutorial

在此处查看更多详细信息,例如http://wiki.bash-hackers.org/howto/getopts_tutorial

回答by Fabricio

You should add spaces between test condition:

您应该在测试条件之间添加空格:

##代码##

I hope this helps.

我希望这有帮助。