我习惯于使用这样的行来测试变量是否具有非空值(或给出消息和保释):
test $variable || (echo "Value of \$variable cannot be null."; exit 1)
我对在我的脚本中使用函数很陌生,但我有一个案例,我需要确保传递一个非空值或退出函数。但是,“或”情况的命令分组在函数内部的工作方式不同。我写了这个小测试脚本来演示:
$ cat -n bubu.sh
1 #!/bin/bash
2
3 read -p "give a value for variable \$foo: " -e -i "bar" foo
4
5 function firstfunc {
6 test $1 || (echo "no value"; return 1)
7 echo it looks like \"$1\" is the first value of \$foo
8 return 0
9 }
10
11 function secondfunc {
12 test $1 || return 1
13 echo it looks like \"$1\" is the second value of \$foo
14 return 0
15 }
16 echo "first function:"
17 firstfunc $foo
18 echo returned $?
19
20 echo "second function:"
21 secondfunc $foo
22 echo returned $?
变量有值的情况下的输出是这样的:
$ ./bubu.sh
give a value for variable $foo: bar
first function:
it looks like "bar" is the first value of $foo
returned 0
second function:
it looks like "bar" is the second value of $foo
returned 0
以及没有值的情况下的输出
$ ./bubu.sh
give a value for variable $foo:
first function:
no value
it looks like "" is the first value of $foo
returned 0
second function:
returned 1
在第一个函数中,当没有值时,我得到“或”命令组的第一个命令,并且“无值”回显,但返回命令被传递并执行函数的其余部分,直到返回.
为什么命令分组的括号在函数内部表现不同,或者我还缺少什么?