I need a bash script to do several jobs in the background, three jobs at a time.
I know that I can do this as follows, and to illustrate, I assume that the number of tasks is 6:
./j1 &
./j2 &
./j3 &
wait
./j4 &
./j5 &
./j6 &
wait
However, in this way, if, for example, j2 takes much longer to run j1 and j3, then I will stick to only one background job that has been running for a long time.
An alternative (which is exactly what I want) is that whenever one task is executed, bash should run the next task in the queue in order to support 3 tasks at any given time. Is it possible to write a bash script to implement this alternative, possibly using a loop? Please note that I need to run a lot more jobs, and I expect this alternative method to save me a lot of time.
Here is my script project, which I hope you can help me verify that it is correct and improve it since I am new to writing scripts in bash. The ideas in this script are taken and modified from here , here and here ):
for i in $(seq 6)
do
while (( (( $(jobs -p | wc -l) )) >= 3 ))
do
sleep 5
done
jobs -x ./j$i &
done
wait
, , script . bash, - .
.