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 parallelise 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.
Try encapsulating your adding step into a function or a temporary script, but send the items to a file instead. I think you will need some command that I can't remember on top of my head for dealing with file lock. See if you need to export things too. Then you source the file at the end. Something like:
Try encapsulating your adding step into a function or a temporary script. See if you need to export things too. Something like:
GNU Parallel is good at doing stuff in parallel :-)
Sample Output
I am suggesting you do - but Charles kindly points out that this is a known
bash
pitfall:Charles' suggested solution is:
You are looking for
parset
(part of GNU Parallel since 20170422) orenv_parset
(available since 20171222):parset
is supported in Bash/Ksh/Zsh (including arrays), ash/dash (without arrays).