我正在用bash脚本调用用C ++编写的命令(在Ubuntu 10.10上)。该命令抛出异常并终止,脚本将中止。
即使使用“set + e”或“command || true”,脚本也不会继续。
如何强制脚本继续?
答案 0 :(得分:3)
shell脚本可以使用“trap”命令捕获除9(KILL)之外的任何信号。特殊信号名称“ERR”表示任何非零错误状态。
trap 'error=1' ERR
while true; do
run-external-program
code="$?"
if [[ -n "$error" ]]; then
echo "Caught an error! Status = $code"
error= # reset the error
elif [[ "$code" != 0 ]]; then
echo "Program exited with non-zero code: $code"
fi
done
您还可以通过空命令告诉shell忽略错误:
trap '' ERR