You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

设置set -o errexit后Bash脚本未在首个错误退出的原因排查

Why Command #2 Doesn't Fail as Expected

The key difference comes down to a critical exception in how Bash's errexit (set -e) option behaves when commands are part of an && or || chain. Let's break this down step by step:

First, Recap the Relevant Bash Options

  • errexit: Terminates the script immediately if a command exits with a non-zero status, except in specific cases we'll cover.
  • pipefail: Makes the exit status of a pipeline equal to the last non-zero exit status of any command in the pipeline (instead of just the last command's status).

Analysis of Command #1

$ /bin/bash -c 'set -o pipefail -o errexit && my_test | ts "%FT%T"'
  1. We enable both pipefail and errexit first.
  2. When my_test runs:
    • The ltt -y command fails (non-zero exit code). Since errexit is active, this immediately terminates my_test (the rest of the function's commands don't run), so my_test exits with the same non-zero code as ltt.
    • With pipefail enabled, the entire pipeline my_test | ts inherits that non-zero exit code.
    • This pipeline is the final command in the script and is not part of an &&/|| chain. So errexit kicks in, terminating the entire bash -c script immediately—hence why Command #1 fails as expected.

Analysis of Command #2

$ /bin/bash -c 'set -o pipefail -o errexit && my_test | ts "%FT%T" && date +%s'
  1. Again, we enable pipefail and errexit.
  2. The pipeline my_test | ts fails (same non-zero exit code as Command #1).
  3. Here's the critical difference: this pipeline is part of an && chain (followed by date +%s). Bash's errexit option explicitly does not terminate the script when a failing command is part of an && or || sequence (and is not the final command in that sequence).
  4. Since the pipeline fails, the && operator skips the subsequent date +%s command. However, because the failure is part of an && chain, errexit doesn't trigger an immediate exit. The script runs to completion, returning the non-zero exit code of the pipeline—but it doesn't "fail" in the sense of being terminated early like Command #1.

In Short

Command #1's pipeline is a standalone final command, so its failure triggers errexit. Command #2's pipeline is part of an && chain, which exempts it from the errexit termination rule—even though the pipeline itself fails, the script continues to run until the end.

内容的提问来源于stack exchange,提问作者Ankur Agarwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:48:40