2

How to know if a background jobs are finished in shell script?

n=0
while [ $n le 10 ]
do 
dosomething &
n= `expr $n + 1`
done

how can we know all dosomething processes completed or not?

after completion i want to print echo "done"

Pavan
  • 507
  • 1
  • 3
  • 15

2 Answers2

3

You could use wait, like so:

n=0
while [ $n le 10 ]
do 
  dosomething &
done
wait
# all dosomething are finished here

If you will need to wait for just a few of them you could use wait $pid, to wait for a specific pid, which you get by executing $!, which means give me the pid of the last command.

EDIT:

I've seen that there are two questions on the matter, have a look at them:

the second of which seems exactly a copy of your question, I'm voting to close this.

Community
  • 1
  • 1
Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
0

You could use the following:

for i in {1..10}; do 
    command &
done; wait

It gets slightly shorter using the for loop and a range of numbers.

  • But it does something different. The OP example runs 10 subtasks *in parallel*. Yours does them one after another. (`in {1..10}` is better than OP, though.) – rici Dec 16 '13 at 18:05
  • @rici Good point, I'll change it back. –  Dec 16 '13 at 18:08