I want to create a for loop where I always call N
functions simultaneously. They do not depend on each other, I simply want to kind of run this loop in parallel.
My idea is to call my function as a background process and after every Nth call I want to wait for all background processes.
But somehow it does not wait... I'm sure I'm missing something obvious.
#!/bin/bash
fun(){
for i in {1..5}
do
echo $i
sleep 1s
done
}
N=2
(
for k in {1..8}
do
((i=i%N))
# ((i++==0)) && (echo "waiting for all background processes" && wait) PROBLEM SOLVED:
((i++==0)) && echo "waiting for all background processes" && wait
echo "i = $i"
fun &
done
wait
)
EDIT: it might have something to do with a subshell... I'm not sure
EDIT2: yes, it was because (echo "waiting for all background processes" && wait)
was executed in a subshell... that was the problem
I found the answer, it was due to (echo "waiting for all background processes" && wait)
was executed in a subshell...
I fixed the code