Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

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.

like image 736
the_prole Avatar asked Oct 31 '25 06:10

the_prole


2 Answers

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 
like image 137
that other guy Avatar answered Nov 01 '25 19:11

that other guy


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=$?!

like image 43
KamilCuk Avatar answered Nov 01 '25 20:11

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!