Search code examples
bashexit-code

Bash: Expect different exit code with set -e


Consider a bash script that is executed with set -e enabled (exit on error).

One of the commands in the script returns an expected non-zero exit code. How to resume the script only when exactly this exit code is returned by the command? Note that exit code zero should also count as an error. A one-line solution would be best.

Example:

set -e

./mycommand  # only continue when exit code of mycommand is '3', otherwise terminate script

...

Solution

  • This would consist of two parts: Detecting error code 3, and turning zero to another

    One possible solution would be like this

    mycommand && false || [ $? -eq 3 ]
    

    The first && operator turns a zero exit code to 1 (with false - change to something else if 1 should be considered "good"), and then use a test to change the "good exit code" to 3.

    A simpler, easier-to-maintain way would be to use a subshell:

    ( mycommand; [ $? -eq 3 ] )
    

    This subshell will run mycommand normally and its exit code would be that of the latter sub-command. Just make sure you don't shopt -s inherit_errexit to ruin this :)