假设这些功能:
return_0() {
return 0
}
return_1() {
return 1
}
然后是以下代码:
if return_0; then
echo "we're in" # this will be displayed
fi
if return_1; then
echo "we aren't" # this won't be displayed
fi
if return_0 -a return_1; then
echo "and here we're in again" # will be displayed - Why ?
fi
为什么我要进入最后一个if
statement?我们不应该与那些0
和1
不符合条件吗?
-a
是test
命令的选项之一(也由[
和[[
实施)。所以你不能单独使用-a
。您可能想要使用&&
,它是AND
列表的控制运算符标记。
if return_0 && return_1; then ...
你可以使用-a
告诉test
“和”两个不同的test
表达式,如
if test -r /file -a -x /file; then
echo 'file is readable and executable'
fi
但这相当于
if [ -r /file -a -x /file ]; then ...
这可能更具可读性,因为括号使表达式的测试部分更清晰。
有关...的更多信息,请参阅Bash参考手册。
&&
,见listsif
语句和各种test
命令和关键字,请参阅conditional constructs当你执行
if return_0 -a return_1; then
echo "and here we're in again" # will be displayed - Why ?
fi
你执行行return_0 -a return_1
。这实际上意味着你将-a
和return_1
作为return_0
的参数传递。如果你想要一个和操作,你应该使用&&
语法。
if return_0 && return_1; then
echo "and here we're in again" # will be displayed - Why ?
fi
理解这一点的有用信息是:
AND和OR列表分别是由
&&
和||
控制运算符分隔的一个或多个管道的序列。 AND和OR列表以左关联性执行。 AND列表具有表单command1 && command2
当且仅当
command2
返回退出状态为零时才执行command1
。OR列表具有表单
command1 || command2
当且仅当
command2
返回非零退出状态时才执行command1
。 AND和OR列表的返回状态是列表中执行的最后一个命令的退出状态。