Fork command in Background using ampersand (&) whe

2019-07-13 18:13发布

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

标签: linux bash shell
1条回答
一夜七次
2楼-- · 2019-07-13 18:47

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.

查看更多
登录 后发表回答