在shell脚本异常处理? [英] Exception handling in shell scripting?
问题描述
我正在寻找在shell脚本的异常处理机制。有没有尝试,赶上相当于机制shell脚本?
I'm looking for exception handling mechanism in shell script. Is there any try,catch equivalent mechanism in shell script ?
推荐答案
有是不是一个真正的的try / catch
在bash(我假设你使用bash)但你可以使用实现了非常类似的行为&放大器;&安培;
或 ||
There is not really a try/catch
in bash (i assume you're using bash), but you can achieve a quite similar behaviour using &&
or ||
.
在这个例子中,你想运行 fallback_command
如果 a_command
失败(返回非零值):
In this example, you want to run fallback_command
if a_command
fails (returns a non-zero value):
a_command || fallback_command
而在这个例子中,要执行 second_command
如果 a_command
成功 (返回0):
a_command && second_command
他们可以很容易地通过一个子shell混合在一起,例如,下面的命令将执行 a_command
,如果成功那么它将运行 other_command
,但如果 a_command
或 other_command
失败, fallback_command
将被执行:
They can easily be mixed together by using a subshell, for example, the following command will execute a_command
, if it succeeds it will then run other_command
, but if a_command
or other_command
fails, fallback_command
will be executed:
(a_command && other_command) || fallback_command
这篇关于在shell脚本异常处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!