Butner
Butner

Reputation: 81

Wait between starting background processes in bash

I have a master script that is scheduled via cron job , The master script would need to call two child scripts parallelly but with a wait time in between (let's say 2 minutes )

below is how the master looks like. How can i add wait time between child 1 and child 2, such that child 2 starts after 1 min though child 1 script is still not finished. Right now i am adding desired wait time in child 2 as workaround but there are several such master that would run both the childs with different wait times hence its tedious to everytime edit 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"

what i tried so far , but unfortunately this waits for child 1 to finish then sleeps 2 min and starts child 2 . Any suggestions ?

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

Upvotes: 0

Views: 602

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295291

A command is run in the background if & -- rather than ;, &&, or a newline -- is used as the command separator that follows it.

Thus, you can start your first backgrounded process with a & after it, and then a subsequent sleep with a ;, &&, or newline:

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

Upvotes: 1

Related Questions