Operating System - HP-UX
1756378 Members
3236 Online
108847 Solutions
New Discussion юеВ

Easy shell script (korn) question

 
SOLVED
Go to solution
Jeanine Kone
Trusted Contributor

Easy shell script (korn) question

I am writing a shell script and in the middle of it I have two commands that I want to run at the same time. I dont want the scipt to continue until BOTH comamnds have completed.

I know I can put an & at the end of the first command so the second one kicks off right away and runs at the same time, but how do I make the shell script wait for the next command if the second one finishes first?

Thanks!
5 REPLIES 5
vtpaulson
Frequent Advisor

Re: Easy shell script (korn) question

Hi,

Use wait command. wait command will wait untill the previous background command finishes. See the man page for more info.

Reg,

Paulson
James R. Ferguson
Acclaimed Contributor

Re: Easy shell script (korn) question

Hi Jeanine:

Consider this:

./mytask1 &
T1=$! #...capture the pid of mytask1...
./mytask2
if [ $? -eq 0 ]; then
echo "task2 completedok"
fi
wait T1 #...wait for mytask1...
if [ $? -eq 0 ]; then
echo "task1 completedok"
fi

...JRF...
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Easy shell script (korn) question

Hi:

By far the easist method is you don't care about the order of execution is:

cmd1.sh &
cmd2.sh &
wait

wait will then pause the parent shell until all child processes have completed.

A variation on this is:
(cmd1.sh; cmd2.sh) &
cmd3.sh
wait

In this case cmd2.sh does not start until cmd1.sh has finished. cmd3.sh run concurrently with cmd1.sh,cmd2.sh. Control does not return until all child processes have finished.

Regards, Clay

If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor

Re: Easy shell script (korn) question

Hi:

By far the easist method is you don't care about the order of execution is:

cmd1.sh &
cmd2.sh &
wait

wait will then pause the parent shell until all child processes have completed.

A variation on this is:
(cmd1.sh; cmd2.sh) &
cmd3.sh &
# I missed this ampersand in the prior posting
wait

In this case cmd2.sh does not start until cmd1.sh has finished. cmd3.sh run concurrently with cmd1.sh,cmd2.sh. Control does not return until all child processes have finished.

Regards, Clay

If it ain't broke, I can fix that.
Magdi KAMAL
Respected Contributor

Re: Easy shell script (korn) question

Hi Jeanine,

example :

cmd1 &
cmd2 &

wait

cmd3

cmd3 will execute only and only if cmd1 AND cmd2 finish ( both of then )

Note : wait is a synchronizing point.


Magdi