了解Bash短路 [英] Understanding Bash short-circuiting
问题描述
首先,我不是Bash专业人士.几个月前,我发现如果同时使用&&
和||
短路运算符和花括号,那么如果第一个语句以真实值退出,则如果true块中的最后一个语句以非括号形式退出,零,则失败块也将被执行.像这样:
First of all I'm not a Bash pro. I discovered few months ago that if I use both the &&
and ||
short circuit operators in sequence with curly braces, then in case the first statement exits with a truthful value, if the last statement in the true block exits non-zero, then the fail block will be executed too. Like this:
returnNumber 0 && {
echo 'OK'
returnNumber 1
} || {
echo 'NG'
}
将输出:
OK
NG
因此,我为此寻求了最简单的解决方案,并提出了以下建议:
So, I looked for the easiest solution for this, and came up with this:
returnNumber 0 && {
echo 'OK'
returnNumber 1
:
} || {
echo 'NG'
}
我知道,很容易省略内置的冒号,但这是解决方法的正确方法吗?
I know, it is easy to leave out the colon builtin, but is it a proper way for a workaround?
推荐答案
这实际上是非常常见的重击陷阱.这不是不是错误.
This is actually a very common Bash pitfall. It is not a bug.
returnNumber 0
的计算结果为true,因此还要对第二个块(由逻辑和&&
连接)进行求值,以确保first && second
的结果仍为true.
第二个块输出OK
,但计算结果为false,因此现在first && second
的结果为false.这意味着还必须对第三部分(用逻辑或||
连接)进行评估,从而也显示NG
.
returnNumber 0
evaluates to true, so the second block (joined by logical and &&
) is evaluated as well to make sure the result of first && second
is still true.
The second block outputs OK
but evaluates to false, so now the result of first && second
is false. This means that the third portion (joined by logical or ||
) must be evaluated as well, causing NG
to be displayed as well.
您应该使用if
语句,而不是依赖&&
和||
:
Instead of relying on &&
and ||
, you should be using if
statements:
if returnNumber 0; then
echo 'OK'
returnNumber 1
else
echo 'NG'
fi
tl; dr:当y
可以返回非零退出状态时,切勿使用x && y || z
.
tl;dr: Never use x && y || z
when y
can return a non-zero exit status.
这篇关于了解Bash短路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!