Why use short-circuiting boolean logic rather than if/then/else in bash?

后端 未结 1 1479
無奈伤痛
無奈伤痛 2021-01-25 03:06

So I\'m now doing quite a bit more bash programming in the last week that I thought I\'d do.

I\'ve seen code that uses [ condition ] && { ... } and

相关标签:
1条回答
  • 2021-01-25 03:44

    [[ ]] is built-in conditional syntax in ksh, adopted by bash, zsh and others. Think of it as a more powerful version of the [ command (which is a different name for the command also called test -- and to be clear, [ is a command, not syntax). It is not a flow control operator, and thus largely off-topic in a discussion about flow control.


    some-command && other-command is short-circuiting boolean logic. That is to say, it's a statement that returns whether both commands return truthful values.

    If and only if some-command succeeds, it is necessary to run other-command to know whether both commands succeed. Thus, as a side effect of this logic operator, it happens to behave in a manner similar to an if statement.

    Similarly, some-command || other-command returns a value which indicates whether one of the commands or the other has succeeded. In order to determine if either of the two is true, it is only necessary to run the one on the right if the the one on the left fails; if the one on the left succeeds, then it is already known a priori that one of the two has succeeded.

    This behavior, and the associated idioms, are common to all languages implementing short-circuiting boolean logic with a well-defined order of operations; no part of this is specific to bash.


    So, why would you use the short-circuiting form? Terseness.

    Why would you use the long form? Correctness, particularly in cases where one needs to combine operations. Consider:

    foo && bar || baz
    

    This looks much like:

    if foo; then bar; else baz; fi
    

    ...however, it has a bug: If bar fails, then baz can be run even if foo succeeded. Thus, the if/then/else form is to be preferred unless one is very certain about desired behavior in the boolean-logic case.

    0 讨论(0)
提交回复
热议问题