I wish to fork a process in background, while capturing output in a bash script.
I can run the following script to ping a list of IPs and it moves each call to background and runs very fast. But it doesn't capture the output of executing the command for further processing.
for i in $(cat list.txt); do
ping -c 1 $i &
done
I wish to run a script of this form with ampersand in the command to push each ping attempt in the background, however it runs very slowly as compared to the script above, which indicates that the script is not executing in parallel.
for i in $(cat list.txt); do
y=$( ping -c 1 $i & )
echo "$y"
done
Please advise how to achieve parallel execution in background while capturing the output of the command
Thanks John
The below script seems slow because you are trying to echo the variable inside the loop. So the last echo will complete only when the all the forked processes are completed, essentially making it sequential.
Instead you can do something like this
This function is as fast as the first one and you have the stdout in the array y.