Understanding Bash short-circuiting

前端 未结 2 1110
一生所求
一生所求 2020-12-07 04:26

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 cur

2条回答
  •  萌比男神i
    2020-12-07 05:03

    This is actually a very common Bash pitfall. It is not a bug.

    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.


    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: Never use x && y || z when y can return a non-zero exit status.

提交回复
热议问题