Search code examples
bashshellkshzsh

set -e and short tests


When I was new to shell scripting, I used a lot of short tests instead of if statements, like false && true.

Then later I learned using set -e, and found my scripts were dying for some reason, and they would work if I replaced the short tests with full if statements. Now, the time has gone, and I still use full if statements only.

The most interesting is that if I open an interactive shell and do the following:

set -e
false && true
echo $?

it returns 1 but the shell doesn't die!

I see that I have been wasting too many lines of code. Anyone could explain to me how can I use set -e with short tests safely, eg. without the script dying?


Solution

  • Regarding my problem of the script unexpectedly dying, it is due to running those short tests in a subshell, or from a function, and said function returns a value different than zero:

    Original example:

    $ set -e
    $ false && true
    $ echo $?
    1
    

    Using a subshell or function:

    $ set -e
    $ (false && true)
    <script died>
    
    $ set -e
    $ variable=$(false && true)
    <script died>
    
    $ set -e
    $ foo()(false && true)
    $ foo
    <script died>
    
    $ set -e
    $ foo(){ false && true; }
    $ foo
    <script died>
    

    Possible solutions:

    $ set -e
    $ (false && true ||:)
    $ (false && true) ||:
    $ (if false; then true; fi)