在 bash 中启动后台进程之间等待

Wait between starting background processes in bash

我有一个通过 cron 作业安排的主脚本,主脚本需要并行调用两个 child 脚本,但中间有一个等待时间(比如 2 分钟)

下面是大师的样子。我如何在 child 1 和 child 2 之间添加等待时间,以便 child 2 在 1 分钟后开始,但 child 1 脚本仍未完成。现在我在 child 2 中添加所需的等待时间作为解决方法,但有几个这样的主控会 运行 两个 child 具有不同的等待时间因此每次编辑都很乏味 child 2。

#!bin/bash
echo "start both the script"
sh child1.sh  & sh child2.sh
echo "child 1 & child 2 finished"
sh child3.sh
echo "child 3 finished"

到目前为止我尝试了什么,但不幸的是,这等待 child 1 完成然后休眠 2 分钟并开始 child 2。有什么建议吗?

 #!bin/bash
    echo "start both the script"
    sh child1.sh  && sleep 2m && sh child2.sh
    echo "child 1 & child 2 finished"
    sh child3.sh
    echo "child 3 finished"

如果 & 而非 ;&& 或换行符用作命令分隔符,则命令在后台 运行跟着它。

因此,您可以使用 & 启动第一个后台进程,然后使用 ;&& 或换行符启动后续睡眠:

#!/bin/bash
echo "Start child1 in the background and child2 in the foreground after a 2m delay" >&2
./child1 & child1_pid=$!
sleep 2m  # note that "2m" is an extension; sleep 120 will work on more systems
./child2; child2_retval=$?

echo "Child2 exited with status $child2_retval"
wait "$child1_pid"; child1_retval=$?
echo "Child1 exited with status $child1_retval"