2

I'm having a shell script as follows.

#!/bin/bash

myfunc() {
   #do something (call a rest service)
   sleep 300
   status=$(get status of the operation performed above)
   while [ "$status" != "succeeded" ]; do
       #do something (call a rest service)
       sleep 300
       status=$(get status of the operation performed above)
   done
}

a=0

while [ $a -lt 1000 ]
do
   a=`expr $a + 1`
   myfunc
done

In best case, above script takes at least 5*1000=5000 seconds to complete running.

Is there a way to make the myfunc call parallel so that we can let the while loop to spawn multiple running instances of the myfunc??

Note: Somehow, this script should wait until all instances of myfunc executions are completed.

Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
Vajira Prabuddhaka
  • 852
  • 4
  • 13
  • 34

2 Answers2

2

I think you could update your script as follow:

#!/bin/bash

myfunc() {
   job_id=$1
   echo "Started job ${job_id}..."

   #do something (call a rest service)
   sleep 300
   status=$(get status of the operation performed above)
   while [ "$status" != "succeeded" ]; do
       #do something (call a rest service)
       sleep 300
       status=$(get status of the operation performed above)
   done

   echo "Terminated job ${job_id}."
}

a=0

while [ $a -lt 1000 ]
do
   echo $a
   a=(($a + 1))
   myfunc $a &
done

wait
echo "Parallel execution terminated."
Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
2

Put them in background.

while [ $a -lt 1000 ]
do echo $a
   a=`expr $a + 1`
   myfunc &
done
wait

Or, in more idiomatic bash,

while (( a < 1000 ))
do echo $((a++))
   myfunc &
done
wait
Paul Hodges
  • 13,382
  • 1
  • 17
  • 36