更新时间:2023-11-29 15:25:58
Bash 中是否有 TRY CATCH 命令?
Is there a TRY CATCH command in Bash?
没有.
Bash 并没有像许多编程语言中那样多.
Bash doesn't have as many luxuries as one can find in many programming languages.
bash 中没有try/catch
;但是,可以使用 &&
或 ||
实现类似的行为.
There is no try/catch
in bash; however, one can achieve similar behavior using &&
or ||
.
使用||
:
如果 command1
失败,则 command2
运行如下
if command1
fails then command2
runs as follows
command1 || command2
同样,使用&&
,command2
会在command1
成功后运行
Similarly, using &&
, command2
will run if command1
is successful
try/catch
最接近的近似如下
{ # try
command1 &&
#save your output
} || { # catch
# save log for exception
}
bash 也包含一些错误处理机制,以及
Also bash contains some error handling mechanisms, as well
set -e
如果任何简单命令失败,它会停止您的脚本.
it stops your script if any simple command fails.
还有为什么不if...else
.它是你***的朋友.
And also why not if...else
. It is your best friend.