I have a for loop in which a function task is called. Each call to the function returns a string that is appended to an array. I would like to parallelize this for loop. I tried using & but it does not seem to work.
Here is the code not parallelised.
task (){ sleep 1;echo "hello $1"; }
arr=()
for i in {1..3}; do
arr+=("$(task $i)")
done
for i in "${arr[@]}"; do
echo "$i x";
done
The output is:
hello 1 x
hello 2 x
hello 3 x
Great! But now, when I try to parallelise it with
[...]
for i in {1..3}; do
arr+=("$(task $i)")&
done
wait
[...]
the output is empty.
UPDATE #1
Regarding the task function:
- The function
tasktakes some time to run and then outputs one string. After all the strings have been gathered, another for loop will loop through the strings and perform some other task. - The order does not matter. The output string can consist of a single line string, possibly with multiple words separated by a white space.