3

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

John
  • 768
  • 1
  • 13
  • 21
  • should'nt the ping should have -c count? Then second script is slow because you fork and then echo it sequentially. where do you want to capture the output to? you can already see it on stdout when i ran it here. – Nuetrino Dec 13 '15 at 11:49
  • hi Nuetrino, well picked, yes there should be a ping count - I have corrected the error. The idea is that I wanted to capture the output in a variable like y rather than so it can be further processed, than just directly print it out on stdout as the first script does. Thanks – John Dec 13 '15 at 12:07
  • 1
    Don't iterate over the output of `cat` with a `for` loop; see [Bash FAQ 1](http://mywiki.wooledge.org/BashFAQ/001). – chepner Dec 13 '15 at 16:19

1 Answers1

1

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.

for i in $(cat list.txt); do 
    y=$( ping -c 4 1 $i & )
    echo "$y"
done

Instead you can do something like this

#!/bin/bash
count=0
for i in $(cat list.txt); do  
    y[count++]=$( ping -c 1 $i & )
done

This function is as fast as the first one and you have the stdout in the array y.

Nuetrino
  • 1,099
  • 1
  • 14
  • 32