代码之家  ›  专栏  ›  技术社区  ›  Michael Gruenstaeudl

确认shell函数的有效输入参数数

  •  1
  • Michael Gruenstaeudl  · 技术社区  · 9 年前

    假设壳函数 my_function 它将接收三个有效的输入参数:

    my_function()
    {
       echo "Three common metasyntactic variables are: $1 $2 $3"
    }
    

    我想在 my_函数 这些输入参数都不是空的。

    $ my_function foo bar baz
    Three common metasyntactic variables are: foo bar baz
    
    $ my_function foo bar  # By default, no error message is given, which I wish to avoid
    Three common metasyntactic variables are: foo bar
    

    编辑1 :

    2 回复  |  直到 9 年前
        1
  •  2
  •   Inian    9 年前

    bash变量 $#

    my_function() {
        (( "$#" == 3 )) || { printf "Lesser than 3 arguments received\n"; exit 1; }
    }
    

    如果你想检查是否有任何论点是 空的 以一种只包含空格的方式,您可以循环参数并检查它。

    for (( i=1; i<="$#"; i++ )); do
        argVal="${!i}"
        [[ -z "${argVal// }" ]] && { printf "Argument #$i is empty\n"; exit 2; }
    done
    

    如果调用参数较少的函数,则将这两者结合起来

    my_function "foo" "bar"
    Lesser than 3 arguments received
    

    my_function "foo" "bar" " "
    Argument #3 is empty
    
        2
  •  0
  •   that other guy    9 年前

    ${var:?} :

    my_function()
    {
       echo "Three common metasyntactic variables are: ${1:?} ${2:?} ${3:?}"
    }
    

    当值为null或未设置时,此操作将失败:

    $ my_function foo bar baz
    Three common metasyntactic variables are: foo bar baz
    
    $ my_function foo bar
    bash: 3: parameter null or not set
    
    $ my_function foo "" baz
    bash: 2: parameter null or not set
    

    类似地,您可以使用 ${1?} 允许空字符串,但对于未设置的变量仍然失败。