the_prole
the_prole

Reputation: 8945

How to optionally handle non-zero exit codes when `set -e`

In script I have set

set -e

then I run command in if statement in said script:

if adb -s emulator-5554 uninstall my.package ; then
    echo "handle emulator command return code here ... "
fi 

I want to get the return code of command emulator-5554 uninstall my.package, and handle the return code depending on its value; I am not able to do this because the command is embedded inside the if statement.

Upvotes: 4

Views: 1592

Answers (2)

KamilCuk
KamilCuk

Reputation: 141060

Another popular mnemonic is && ret=0 || ret=$? or similar. Because assignment ret=$? returns zero exit status, the expression exits with zero status. Yet another popular mnemonic is ret=0; <the command> || ret=$?

adb -s emulator-5554 uninstall my.package && ret=$? || ret=$?

if ((ret == 0)); then
   echo "Yay, success!"
elif ((ret == 1)); then
   echo "Yay, it failed!"
elif ((ret == 2)); then
   echo "Abandon ship!"
else 
   echo "Unhandled error"
fi

Be sure not to write it as || ret=$? && ret=$?!

Upvotes: 6

that other guy
that other guy

Reputation: 123480

Being in an if statement does not affect how you get return codes, and set -e does not apply to conditional commands:

if adb -s emulator-5554 uninstall my.package ; then
    echo "The command succeeded, yay!"
else
    code="$?"
    echo "The command failed with exit code $code"
fi 

Upvotes: 7

Related Questions