Search code examples
bashshort-circuiting

How to emulate C++ `x=x&&f()` in bash


I'm writing this all over the place:

if (( $x == 0 )) ; then
    mycommand
    x=$?
fi

Is there a simpler/briefer way to do this with bash's short-circuiting &&?

EDIT: I don't care about the value of $x other than it's zeroness i.e. success/failure.


Solution

  • So, variable x is just the result of the previous command? If you mean that you have a continuous series of almost identical blocks like:

    if (( $x == 0 )) ; then my_command_1; x=$?; fi
    ....
    if (( $x == 0 )) ; then my_command_N; x=$?; fi
    

    Then, just combine your commands this way

    my_command_1 \
    && ... \
    && my_command_N
    

    [update]

    On the other hand, if the commands are scattered all over the script, I would do either:

    x=true
    $x && my_command_1 || x=false
    ...
    $x && my_command_2 || x=false
    

    Or, more discreet:

    $do my_command_1 || do=:
    ...
    $do my_command_2 || do=:
    

    Or, more probably, through a function:

    function check_and_do { [ -z "$failed" ] && "$@" || failed=ouch; }
    
    check_and_do my_command_1
    ....
    check_and_do my_command_2