简体   繁体   中英

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

...

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 :)

Without using set -e which Charles Duffy pointed out in a comment is problematic:

# don't use set -e

./mycommand
if (( $? != 3 ))
then
    exit
fi

# more script contents follow

You can shorten that to:

# don't use set -e

./mycommand
(( $? != 3 )) && exit

# more script contents follow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM