My script (.ksh) :

cmd1 & cmd2

I want cmd1 to be executed in the background and cmd2 to start executing only after cmd1 has started. But, when I run my script, cmd2 is starting before cmd1, thereby causing me a problem.

How can I solve this issue ?


2 Answers 2


By using the conditional operator && you can force the "finish" of one execution before the other one starts. (I put "finish" in quotes, because what is actually "finishing" is putting the process in the background.)


$ (echo "foo" &) ; echo "bar"

might output


the following

$ (echo "foo" &) && echo "bar"

will output


because the shell needs to determine the exit status of the first command before it can execute the second.


The easiest solution would to add a tiny sleep:

cmd1 & sleep 1 && cmd2

More robust would be to use a wrapper for cmd2 that makes sure the cmd1 is actually running and then proceed.

Something like:

while ! pgrep cmd1; do
    sleep 1

while ! can be replaced with until BTW.

  • Dont we need an "&" after cmd1 so as it run it in the background?
    – Ravi Teja
    Aug 2, 2017 at 9:45
  • @RaviTeja i presume you meant the second one. This goes as a wrapper for cmd2. You need to create a script with this, and it will run cmd2 only when cmd1 is running.
    – heemayl
    Aug 2, 2017 at 9:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .