shell - "Exception handling"在 shell 脚本中

标签 shell zsh

我知道您可以在 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/

相关文章:

linux - 如何将 grep 通过管道传输到使用仅具有读取权限的目录的程序中

Linux shell 脚本 - 在文件的第一行搜索字符串(日期)并将其复制到新文件?

shell - 'date --date' 的 AIX 等效项

macos - OS X 终端在运行 "source kvm.sh"后挂起安装 vNext KVM

macos - 如何将 Brew 添加到路径、Ventura 上的 Fish

c - 运行 C 程序备份 Linux 文件

svn - 如何使用来自 `read` 的变量作为另一个程序的参数?

zsh - 为什么您需要为iTerm中的每个新Shell采购.zshrc?

Zsh 想要自动更正命令,前面有一个 _

Zsh + tmux + oh-my-zsh : Autocomplete produces remnant characters