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

3
  • 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. Commented Dec 13, 2015 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 Commented Dec 13, 2015 at 12:07
  • 1
    Don't iterate over the output of cat with a for loop; see Bash FAQ 1. Commented Dec 13, 2015 at 16:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Tested it before posting. What problem do you see?
That it sleeps for 10s, and so doesn't answer OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.