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

bash中wait命令在后台进程出错时未触发set -e退出脚本的问题

Why set -e Doesn’t Exit the Script When Waiting on a Failing Background Process

Let’s break down why your script keeps printing "Done" even when the background sleep command fails—even with set -e enabled.

The Core Reason: set -e Ignores wait’s Non-Zero Exit Code

set -e (aka errexit) is built to exit the script immediately if a foreground command returns a non-zero exit code. But background processes and the wait command have special behavior here:

  • When you run a command in the background with &, bash treats it as an asynchronous task. It doesn’t monitor its exit status in real time, and set -e won’t react to its failure until you explicitly wait for it.
  • The wait command returns the exit code of the background process it’s waiting for—but set -e does not automatically exit the script if wait returns a non-zero code. This is a deliberate bash design choice: background processes are often used for parallel work, and the shell assumes you’ll want to handle their failure status manually rather than having the script exit abruptly.

Let’s Walk Through Your Script

In your modified script:

#!/bin/bash
set -e
echo "Sleeping..."
sleep SOMETHING_STRANGE_AND_WRONG &
wait
echo "Done"
exit 0

The sleep command fails right away (since SOMETHING_STRANGE_AND_WRONG isn’t a valid argument), returns a non-zero exit code, and wait picks up that code. But set -e ignores this non-zero exit code from wait, so the script continues to run and prints "Done".

How to Make the Script Exit on Background Failure

If you want the script to exit when the background process fails, you need to explicitly check the exit code returned by wait. Here’s a straightforward way to do it:

#!/bin/bash
set -e
echo "Sleeping..."
# Run the command in the background and save its PID
sleep SOMETHING_STRANGE_AND_WRONG &
PID=$!
# Wait for the process and capture its exit code
wait $PID
EXIT_CODE=$?
# Exit the script if the background process failed
if [ $EXIT_CODE -ne 0 ]; then
    echo "Background process failed with exit code $EXIT_CODE"
    exit $EXIT_CODE
fi
echo "Done"
exit 0

Or you can condense the check into one line for brevity:

wait $PID || exit $?

This explicitly tells the script to exit if the background process returns a non-zero code, bypassing the set -e exception for wait.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:23:14