在后台可能有几个命令,但等待所有结果,如果命令失败,则失败 [英] Is it possible to several commands in the background but wait for all results and fail the script if an command fails

查看:199
本文介绍了在后台可能有几个命令,但等待所有结果,如果命令失败,则失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CI脚本,我想通过在后台运行几个东西加快。

I have a CI script that I want to speed up by running several things in the background. I want the script wait for all processes and check each one to see if it failed.

这里aa简化:

#!/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


推荐答案

是的。

您可以使用 bash code>等待一个或多个子进程完成,在这种情况下,我们提供 PID 等待它。 wait 可以选择不带参数,在这种情况下,它会等待所有后台进程终止。

You can use the wait command in bash to wait for completion on one or more sub-processes to terminate in which case we provide the PID to wait on it. Also wait can optionally take no arguments in which case it waits for all background process to terminate.

#!/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 的精彩建议。它像

To identify the jobs when the fail, it is best to loop over the list of background jobs and log their exit-code for visibility. Thanks to wonderful suggestion by chepner. It goes like

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

这篇关于在后台可能有几个命令,但等待所有结果,如果命令失败,则失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆