我正在寻找shell脚本中的异常处理机制。shell脚本中是否有try、catch等效机制?
发布于 2011-08-06 03:13:46
bash中并没有真正的try/catch (我假设您正在使用bash),但是您可以使用&&或||来实现非常类似的行为。
在此示例中,如果a_command 失败(返回一个非零值),则要运行:
a_command || fallback_command在此示例中,如果a_command 成功执行(返回0),则希望执行:
a_command && second_command通过使用子subshell可以很容易地将它们混合在一起,例如,以下命令将执行a_command,如果成功,它将运行other_command,但如果a_command或other_command失败,则将执行fallback_command:
(a_command && other_command) || fallback_command发布于 2011-08-07 11:42:02
if/else结构和退出代码可以帮助您伪造一些代码。这应该可以在Bash或Bourne (sh)中工作。
if foo ; then
else
e=$? # return code from if
if [ "${e}" -eq "1"]; then
echo "Foo returned exit code 1"
elif [ "${e}" -gt "1"]; then
echo "Foo returned BAD exit code ${e}"
fi
fi发布于 2016-06-22 21:06:25
{
# command which may fail and give an error
} || {
# command which should be run instead of the above failing command
}https://stackoverflow.com/questions/6961389
复制相似问题