1

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 ?

1

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
done
cmd2

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 '17 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 '17 at 9:47
1

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.)

While

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

might output

bar
foo

the following

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

will output

foo
bar

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.