最近写个shell的发布脚本,有个地方希望能够达到python类似的try/except的效果。然而shell的命令中似乎并没有直接类似的命令,但是万能的stackoverflow依旧给出了一个不错的答案:https://stackoverflow.com/questions/6961389/exception-handling-in-shell-scripting
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 ||
.
In this example, you want to run fallback_command
if a_command
fails (returns a non-zero value):
a_command || fallback_command
And in this example, you want to execute second_command
if a_command
is successful (returns 0):
a_command && second_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