【问题标题】:Functional difference between if-then and command groupif-then 和命令组的功能区别
【发布时间】:2013-07-05 01:07:20
【问题描述】:

使用简单的 if-then 语句是否有任何功能优势,例如

if [ … ]; then
do

使用带有命令组的短路列表评估器,例如

[ … ] && {
}

当然,if-then 是标准的写法,但是从功能的角度来看,有什么实际的区别/优势吗?

使用() 而不是{} 会生成一个新的子shell,从而为 if-then 块内的变量创建一个新的范围。

【问题讨论】:

    标签: bash if-statement sh short-circuiting


    【解决方案1】:

    不是你的例子,而是常见的

    condition && foo || bar
    

    和

    不一样
    if condition
    then
      foo
    else
      bar
    fi
    

    在前一种情况下,bar 不仅会在condition 失败时运行,而且在foo 失败时也会运行。

    【讨论】:

    • 会和笨拙的condition && { foo; false; } || bar一样吧?
    • 如果你的意思是condition && { foo; true; } || bar,那么是的。
    • 嗯,是的,我是想写condition && { foo; :; } || bar
    • 我不完全确定这是否正确。不做shell短路评估?所以condition && foo || bar与(condition && foo) || bar(运算符优先级)基本相同,这意味着如果condition为假,foo无论如何都不会被执行。还是布尔求值在普通 shell 中的工作方式不同?
    • @knittl 是的,问题是当condition 为真,而foo 为假时。当condition 为假或foo 为真时,一切都很好。
    猜你喜欢
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 2019-04-26
    • 2021-12-04
    相关资源
    最近更新 更多