Search code examples
shellexit-code

In shell, how do I test a return code recorded from $?


Silly sort of question, but...

I can exit if a command fails easily enough:

command || exit $?

If I want to interpose something between the command and the exit, I can test the return code vs 0, or just exit from a subshell:

command ; rc=$?
echo That command returned $rc
[ $rc -eq 0 ] || exit $rc
# or
( exit $rc ) || exit $rc

But I don't like test vs 0, because it makes 0=true explicit.

And while I like ( exit $rc ) because it avoids explicit 0, a subshell seems heavyweight and using exit twice seems redundant.

Is there some better alternative?


Solution

  • Not quiiiite what I had in mind, but close enough for me because I generally only care about failure:

    $ bash
    bash-3.2$ false || exit $? $( echo worbly boo $? > /dev/tty )
    worbly boo 1
    exit
    

    It short-cuts the $( ) conveniently, so no subshell except in an error case.

    It also handles failures within the $( ) fairly elegantly:

    bash-3.2$ false || exit $? $( ( foo ; echo $? ) > /dev/tty )
    bash: foo: command not found
    127
    exit