假设这些功能:
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
语句?
难道我们不应该使用那些 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 ...
这可能更具可读性,因为括号使表达式的 test 部分更清晰。
有关...的更多信息,请参阅 Bash 引用手册
&&
,参见listsif
语句和各种test
命令和关键字,参见 conditional constructs
关于bash - SHELL - IF 语句中的 AND 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55729300/