I'd like to start a sequence of background job in a while loop in a bash script:
END=10
i=0;
while [ $i -lt $END ]
do
(SOME COMMAND;\
sleep 3;
SOME COMMAND 1;\
SOME COMMAND 2;\
SOME COMMAND 3;) &
i=`expr $i + 1`
done
And outside this while loop I'd like to wait until all these 10 background job all finished SOME COMMAND 1
and then proceed, so the psudo code is something like:
until [the number of process that finished SOME COMMAND 1 is greater or equal to $END];
do
sleep 0.5
done
What I tried to do is to add another counter like this:
true_started_cnt=0
END=10
i=0;
while [ $i -lt $END ]
do
(SOME COMMAND;\
sleep 3;
SOME COMMAND 1;\
true_started_cnt=`expr $true_started_cnt + 1`;\
SOME COMMAND 2;\
SOME COMMAND 3;) &
i=`expr $i + 1`
done
until [ $true_started_cnt -ge $END ]
do
echo "Waiting for initial period for all streams to finish"
sleep 0.5
done
But this seems not working, possibly because of simultaneous write of the same global var by multiple bg jobs. I wonder how to achieve my intention in this piece of code.
Referring to this post, I'm also trying:
echo 1 >/dev/shm/foo
END=10
i=0;
while [ $i -lt $END ]
do
(SOME COMMAND;\
sleep 3;
SOME COMMAND 1;\
echo $(($(</dev/shm/foo)+1)) >/dev/shm/foo;\
SOME COMMAND 2;\
SOME COMMAND 3;) &
i=`expr $i + 1`
done
until [ $(echo $(</dev/shm/foo)) -ge $END ]
do
echo "Waiting, true_started_cnt=$(echo $(</dev/shm/foo))"
sleep 1
done
But still not working.