我有一个 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
Yes.
您可以使用wait https://linux.die.net/man/3/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"
Update:-
要在失败时识别作业,最好循环遍历后台作业列表并记录其退出代码以供可见性。感谢以下的精彩建议chepner https://stackoverflow.com/users/1126841/chepner。它就像
#!/bin/bash
for p in $(jobs -p)
do
wait "$p" || { echo "job $p failed" >&2; exit; }
done
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)