mde*_*ous 108
try/catchbash中没有真正的(我假设你正在使用bash),但你可以使用&&或实现一个非常相似的行为||.
在此示例中,您希望fallback_command在a_command 失败时运行(返回非零值):
a_command || fallback_command
Run Code Online (Sandbox Code Playgroud)
在本例中,second_command如果a_command 成功则要执行(返回0):
a_command && second_command
Run Code Online (Sandbox Code Playgroud)
它们可以通过使用子shell轻松混合在一起,例如,执行以下命令a_command,如果成功,它将运行other_command,但是如果a_command或者other_command失败,fallback_command将执行:
(a_command && other_command) || fallback_command
Run Code Online (Sandbox Code Playgroud)
bri*_*cer 12
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
Run Code Online (Sandbox Code Playgroud)
小智 5
{
# command which may fail and give an error
} || {
# command which should be run instead of the above failing command
}
Run Code Online (Sandbox Code Playgroud)