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.
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
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=$?!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With