我知道您可以在 shell 脚本中使用快捷 bool 运算符来执行某种异常处理,如下所示:
my_first_command && my_second_command && my_third_command
但是随着您想要链接的命令数量的增加,这很快就会变得不可读和不可维护。如果我正在编写脚本(或 shell 函数),是否有一种好方法可以让脚本或函数在第一个非零返回码处停止执行,而不用写在一条大行上?
(我使用
zsh
,所以如果有仅适用于 zsh
的答案对我来说没问题。)
最佳答案
-e
选项这样做:
ERR_EXIT (-e, ksh: -e)
If a command has a non-zero exit status, execute the ZERR trap,
if set, and exit. This is disabled while running initialization
scripts.
你应该能够把它放在shebang线上,比如:
#!/usr/bin/zsh -e
大多数 shell 都有这个选项,它通常被称为
-e
.
关于shell - "Exception handling"在 shell 脚本中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571019/