如果不使用&b;& amp ;,则使用bash的正确方法是什么?||捷径? [英] What is the correct way to use the bash if else && || shortcut?
问题描述
我遇到了一些奇怪的行为(也许并不奇怪,但我不理解!)
I have come across some strange behavious (well probably not strange but I don't understand it !)
我想使用bash速记语法编写一些if/e,se语句:
I want to write some if / e,se statements using the bash shorthand syntax:
[[ 1 -eq 1 ]] && echo "true" || echo "false"
以上代码的输出为:
true
现在,上面的代码实际上可以正常工作.但是下面的代码没有:
Now the code above actually works fine. But this next code does not:
[[ 1 -eq 1 ]] && infMsg "true" || infMsg "false"
infMsg 只是一个函数.上面的代码输出为:
infMsg is just a function. The output from the above code gives:
true
false
我只希望它说"true".
I only want it to say 'true'.
在&&中,我是否缺少某些东西?||语法处理函数的退出代码?
Is there something I am missing in the way the && || syntax handles exit codes from functions ?
推荐答案
我怀疑您的'infMsg'退出代码不为0(成功).如果我们分解第一段代码:
I suspect your exit code for 'infMsg' is not 0 (success). If we break down the first piece of code:
[[ 1 -eq 1 ]] && echo "true" || echo "false"
发生了什么事
-
[[1 -eq 1]]&&因为
&&
的优先级高于||
(更多信息[此处语句.(&&->如果第一部分是正确的,请运行第二部分) - 现在我们有了
||回显"false"
.由于上半部分(echo"true"
)返回true,因为回声已成功打印((||->如果第一个部分为false,请运行第二个部分),所以实际上该部分没有执行.部分).).
- The
[[ 1 -eq 1 ]] && echo "true"
portion of code is evaluated first since&&
has a higher precedence than||
(more info[here1) - The first half of that returns true. Then, since the first half was true, the second half executes the
echo "true"
statement. (&& -> If part one is true, run the second part) - Now we have the
|| echo "false"
. This part actually doesn't get executed since the first half (echo "true"
) returned true since the echo printed successfully ((||-> If part one is false, run the second part).).
现在,如果我们分解第二段代码:
Now if we break down the second piece of code:
[[ 1 -eq 1 ]] && infMsg "true" || infMsg "false"
最有可能发生的事情 是:
What's most likely happening is:
-
[[1 -eq 1]]&&infMsg"true"
被评估.第一面是正确的.然后,由于前半部分为true ,因此后半部分执行infMsg"true"
语句.(&&->如果第一部分是正确的,请运行第二部分). - 现在我们有
||infMsg"false"
.如果前一个命令的infMsg"true"
没有返回解释为成功的状态代码(0),则前半部分将被解释为false,从而触发infMsg"false"
((||->如果第一部分为假,请运行第二部分).)..
[[ 1 -eq 1 ]] && infMsg "true"
is evaluated. The first side is true. Then, since the first half was true, the second half executes theinfMsg "true"
statement. (&& -> If part one is true, run the second part).- Now we have
|| infMsg "false"
. If theinfMsg "true"
from the previous command didn't return a status code that is interpreted as success (0), the first half is interpreted as false, triggering theinfMsg "false"
((||-> If part one is false, run the second part).)..
要移至此处的重要信息:
The important info to pull away here:
- ||仅在前半部分为FALSE时才运行后半部分.
- &&如果前半部分为TRUE,则仅运行后半部分.
这篇关于如果不使用&b;& amp ;,则使用bash的正确方法是什么?||捷径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!