在设置-e时如何有选择地处理非零退出代码

时间:2019-05-06 17:38:17

标签: linux bash

在脚本中我已设置

set -e

然后我在上述脚本的if语句中运行命令:

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

我想获取命令emulator-5554 uninstall my.package的返回码,并根据其值来处理返回码;我无法执行此操作,因为该命令嵌入在if语句内。

2 个答案:

答案 0 :(得分:6)

进入const map = { small: 1, large: 2 }; const closestSize = ['small', 'large'].find((size) => !!map[size]); // errors Type 'undefined' cannot be used as an index type.ts(2538) but we know that either small or large will be found return map[closestSize]; 语句不会影响您获取返回码的方式,并且if不适用于条件命令:

set -e

答案 1 :(得分:2)

另一个流行的助记符是&& ret=0 || ret=$?或类似名称。因为赋值ret=$?返回零退出状态,所以表达式以零状态退出。还有一种流行的助记符是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

请确保不要将其写为|| ret=$? && ret=$?

相关问题