【问题标题】:Confirming the number of valid input arguments of a shell function确认 shell 函数的有效输入参数的数量
【发布时间】:2017-09-19 16:16:10
【问题描述】:

假设一个 shell 函数 my_function 期望接收三个有效的输入参数:

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

我想在my_function 中包含一个测试,评估函数是否确实收到了三个输入参数并且这些输入参数都不是空的。

$ 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: 如上所述,我正在寻找的代码不仅可以确认输入变量的数量,而且还可以确认它们都不是空的。这第二个方面是相关的,因为输入变量可能是从其他函数传递的变量本身。

【问题讨论】:

  • 使用 $# 检查脚本/函数的参数数量。

标签: bash function shell if-statement arguments


【解决方案1】:

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】:

您可以防御性地断言此类变量是使用${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?} 来允许空字符串,但对于未设置的变量仍然会失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 2015-04-02
    • 2012-07-09
    相关资源
    最近更新 更多