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

如果未满足所需的参数计数,我希望我的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

我究竟做错了什么?


就像任何其他简单的命令一样, [ ... ]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引号的条件分组,模式匹配(与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.

如果您需要将它与[[ ]]其他功能组合起来,这应该会很有帮助。

参考文献:

  • 打击条件表达式
  • 有条件的构造
  • 模式匹配
  • 分词
  • 文件名扩展(prev。路径名扩展)

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

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

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

    我会用:

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

    要么:

    if [ $# -eq 1 ]; then
    
    链接地址: http://www.djcxy.com/p/24145.html

    上一篇: Check number of arguments passed to a Bash script

    下一篇: Redirect all output to file