bash - 是否可以在后台执行多个命令,但等待所有结果并在命令失败时使脚本失败

标签 bash shell curl continuous-integration sh

我有一个 CI 脚本,我想通过在后台运行一些东西来加速它。我希望脚本等待所有进程并检查每个进程以查看是否失败。

这里有一个简化:

#!/bin/bash

set -e

bg()
{
    sleep .$[ ( $RANDOM % 10 ) + 1 ]s
}

bg2()
{
    sleep .$[ ( $RANDOM % 10 ) + 1 ]s
    exit 1
}

bg &   # will pass after a random delay 
bg2 &  # will fail after a random delay


# I want the output of the program to be a failure since bg2 fails

最佳答案

是的。

您可以使用wait bash 中的命令等待一个或多个子进程完成才能终止,在这种情况下,我们提供 PID 来等待它。另外,wait 可以选择不带任何参数,在这种情况下,它会等待所有后台进程终止。

示例:-

#!/bin/bash

sleep 3 &

wait "$!"     # Feeding the non-zero process-id as argument to wait command.
              # Can also be stored in a variable as pid=$(echo $!)

# Waits until the process 'sleep 3' is completed. Here the wait 
# on a single process is done by capturing its process id

echo "I am waking up"

sleep 4 &
sleep 5 &

wait          # Without specifying the id, just 'wait' waits until all jobs 
              # started on the background is complete.

# (or) simply
# wait < <(jobs -p)     # To wait on all background jobs started with (job &)

echo "I woke up again"

更新:-

要在失败时识别作业,最好循环遍历后台作业列表并记录其退出代码以供可见。感谢chepner的精彩建议。事情就像这样

#!/bin/bash
for p in $(jobs -p)
do
     wait "$p" || { echo "job $p failed" >&2; exit; }
done

关于bash - 是否可以在后台执行多个命令,但等待所有结果并在命令失败时使脚本失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40215226/

相关文章:

linux - 在 Bash 中捕获逻辑的返回输出

c++ - 带有命令行参数的 C++ Makefile 和 Bash 脚本

linux - 为什么我无法在 sed 替换中转义单引号但使用\x27 有效?

ssl - 使用 `-k` 和不使用 `-k` 进行 curl

使用 curl 进行 PHP 抓取 - 我该如何调试

bash - 在执行第一个命令后执行命令

c++ - 一种为在 bash 中调用的程序提供参数的方法

bash - shell脚本将标签插入到xml中?

bash - 当子脚本之一失败时不退出 bash 脚本

amazon-web-services - 通过curl命令从本地目录或AWS S3导入rundeck中的作业