我知道在shell脚本中可以使用布尔运算符来进行某种异常处理,如下所示:
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
-e
。