首页 文章

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

提问于
浏览
542

如果不满足所需的参数计数,我希望我的Bash脚本能够打印错误消息 .

我尝试了以下代码:

#!/bin/bash
echo Script name: $0
echo $# arguments 
if [$# -ne 1]; 
    then echo "illegal number of parameters"
fi

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

test: line 4: [2: command not found

我究竟做错了什么?

7 回答

  • 26

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

    [ "$#" -ne 1 ] && ( usage && exit 1 ) || main
    

    这分解为:

    • 测试参数大小的bash变量$#not equals 1(我们的子命令数)

    • 如果为true则调用usage()函数并退出状态1

    • else调用main()函数

    想一想:

    • usage()可以简单回显"$0: params"

    • main可以是一个长脚本

  • 0

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

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

    我希望这有帮助 .

  • 31

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

    我会用:

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

    要么:

    if [ $# -eq 1 ]; then
    
  • 821

    如果您想要安全,我建议使用getopts .

    这是一个小例子:

    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
    

    在这里查看更多详细信息http://wiki.bash-hackers.org/howto/getopts_tutorial

  • 54

    如果你正在处理数字,那么使用arithmetic expressions可能是个好主意 .

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

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

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

    要么

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

    在Bash中,更喜欢使用 [[ ]] ,因为它不是表达式的一部分 .

    [[ $# -ne 1 ]]
    

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

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

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

    对于纯算术表达式,使用 (( )) 可能仍然会更好,但是通过将表达式放在单个字符串参数中,它们仍然可以在 [[ ]] 中使用算术运算符,如 -eq-ne-lt-le-gt-ge

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

    如果您需要将它与 [[ ]] 的其他功能结合使用,这应该会有所帮助 .

    参考文献:

  • 0

    如果你只对缺少一个特定的参数感兴趣,Parameter Substitution很棒:

    #!/bin/bash
    # usage-message.sh
    
    : ${1?"Usage: $0 ARGUMENT"}
    #  Script exits here if command-line parameter absent,
    #+ with following error message.
    #    usage-message.sh: 1: Usage: usage-message.sh ARGUMENT
    

相关问题