Bash IF语句中的SHELL和操作
假设这些功能:Bash IF语句中的SHELL和操作,bash,shell,if-statement,ksh,Bash,Shell,If Statement,Ksh,假设这些功能: 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
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
。您可能需要使用&&
,这是和
列表的控制运算符标记
if return_0 && return_1; then ...
您可以使用-a
告诉test
to“和”两个不同的test
表达式,如
if test -r /file -a -x /file; then
echo 'file is readable and executable'
fi
但这相当于
if [ -r /file -a -x /file ]; then ...
因为括号使表达式的测试部分更清晰,所以它可能更可读
有关…的更多信息,请参阅Bash参考手册
,请参阅&&
语句和各种if
命令和关键字,请参阅test
if return_0 -a return_1; then
echo "and here we're in again" # will be displayed - Why ?
fi
执行行return\u 0-a return\u 1
。这实际上意味着将-a
和return\u 1
作为参数传递给return\u 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
command1 || command2
当且仅当command1
返回零退出状态时,才会执行command2
或列表具有以下形式:
command1 && command2
command1 || command2
command2
在且仅当command1
返回非零退出状态时执行。and和OR lists的返回状态是列表中执行的最后一个命令的退出状态