我有一个 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/