用 set -euo pipefail 让 Bash 脚本快速失败

加上严格模式,遇到错误、未定义变量或管道失败时立即退出。

macOSBash 脚本Shell脚本低风险
在脚本开头写 set -euo pipefail,任何错误、未定义变量或管道失败都会让脚本退出。

01命令

命令
$ set -euo pipefail

02作用说明

默认情况下脚本在命令失败后仍会继续,容易在自动化中把小错变成大错。严格模式中 -e 遇错退出,-u 拒绝未定义变量,-o pipefail 让管道内部的失败暴露出来。这正是 shell 的用武之地,图形界面无法提供这种自动化控制。

03风险

风险低风险
使用条件macOS default zsh/bash (bash 3.2+; some features need bash 4+ via Homebrew)
系统兼容性macOS with bash 3.2+ (GNU bash 4+ via Homebrew for advanced features)
!注意: 有些命令本就会返回非零;用 || true 或显式 if 处理它们,而不是取消严格模式。

04撤销

✓无需撤销——该命令不会改变持久状态。

05来源

  • bash.1.en.html manual page
    Debian · technical · 2026-09-20
    依据: The bash manual page documents the set builtin and its options.

最后验证: 2026-10-13 · 分类: 开发者