简体   繁体   English

如果“set + e”不够,如何保持bash脚本运行?

[英]How to keep a bash script running when “set +e” is not enough?

I am calling a command written in C++ from a bash script (on Ubuntu 10.10). 我正在用bash脚本调用用C ++编写的命令(在Ubuntu 10.10上)。 The command throws an exception and terminates, and the script is aborted. 该命令抛出异常并终止,脚本将中止。

Even with "set +e" or "command || true", the script will not continue. 即使使用“set + e”或“command || true”,脚本也不会继续。

How can I force the script to continue? 如何强制脚本继续?

The shell script can trap any signal except 9 (KILL), with the "trap" command. shell脚本可以使用“trap”命令捕获除9(KILL)之外的任何信号。 The special signal name "ERR" means any non-zero error status. 特殊信号名称“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

You can also tell the shell to ignore errors with an empty command: 您还可以通过空命令告诉shell忽略错误:

   trap '' ERR

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM