2010-12-10 98 views
4

我正在调用bash脚本(在Ubuntu 10.10上)用C++编写的命令。该命令抛出异常并终止,并且脚本被中止。如何在“set + e”不够时保持bash脚本运行?

即使使用“set + e”或“command || true”,脚本也不会继续。

如何强制脚本继续?

+0

请出示你的脚本,和一个小的C++程序演示该问题。 – 2010-12-10 20:54:20

+0

'while:do done'或将stderr重定向到/ dev/null如此:'command 2>/dev/null'?也发布你的脚本! – Cipi 2010-12-10 20:56:59

+0

它是否为段错误? – 2010-12-11 01:03:55

回答

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 
+0

您可能需要使用'set -E'(errtrace)才能保持一致。通常,子命令不会继承错误陷阱 – Hamy 2014-06-18 08:02:12