I'm trying to run a command in parallel by detaching it:
sleep 2s &
#!/bin/bash
for ((i=1;i<=3;i++)); do
sleep 2s &
pids[${i}]=$!
done
for pid in ${pids[*]}; do
wait $pid
done
Which will spawn 3x the command 'sleep 2s' and wait for the commands to be finished
This is executed as expected (2 seconds):
pi@raspberrypi:~/scripts $ time ./test.sh
real 0m2.029s user 0m0.022s sys 0m0.052s
When I try to capture the output of the process, the execution changes from parallel to sequential. The execution time is now 6 seconds (3x 2 seconds)
output[${i}]=$(sleep 2s &)
#!/bin/bash
for ((i=1;i<=3;i++)); do
output[${i}]=$(sleep 2s &)
pids[${i}]=$!
done
for pid in ${pids[*]}; do
wait $pid
done
pi@raspberrypi:~/scripts $ time ./test.sh
real 0m6.030s user 0m0.006s sys 0m0.015s
Any ideas on how to capture the output whilst running the commands in parallel? Thanks!