确认shell函数

时间:2017-09-19 16:16:10

标签: bash function shell if-statement arguments

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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