简体   繁体   English

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

[英]Confirming the number of valid input arguments of a shell function

Assume a shell function my_function that expects to receive three valid input arguments: 假设一个外壳函数my_function期望接收三个有效的输入参数:

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

I would like to include a test within my_function that assesses if the function has indeed received three input arguments and that none of these input arguments is empty. 我想在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

How would I implement that? 我将如何实施?

Edit 1 : As emphasized above, I am looking for code that not only confirms the number of input variables, but also confirms that none of them is empty. 编辑1 :如上所述,我正在寻找的代码不仅要确认输入变量的数量,还要确认它们都不为空。 This second aspect is relevant because the input variables may be variables themselves that are passed from other functions. 第二个方面很重要,因为输入变量可能是从其他函数传递来的变量本身。

The bash variable $# contains the length of the command line arguments passed to the script function. bash变量$#包含传递给脚本函数的命令行参数的长度。

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

Also if you wanted to check if any of the argument is empty in a way containing only white-spaces, you can loop over the arguments and check it. 同样,如果您想以仅包含空格的方式检查任何自变量是否为 ,则可以遍历自变量并对其进行检查。

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

Combining these two, if you call a function with fewer arguments 如果您以较少的参数调用函数,则将两者结合

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

and for empty arguments, 对于空参数,

my_function "foo" "bar" " "
Argument #3 is empty

You can defensively assert that such variables are set with ${var:?} : 您可以辩称这些变量是用${var:?}

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

This will fail when the values are null or unset: 当值为空或未设置时,这将失败:

$ 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

Similarly, you can use ${1?} to allow empty strings, but still fail for unset variables. 同样,您可以使用${1?}来允许空字符串,但是对于未设置的变量仍然会失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM