Bash脚本编写和捕获输出时,在后台使用&符(&)在背景中派生命令 [英] Fork command in Background using ampersand (&) when Bash scripting and capture output

查看:57
本文介绍了Bash脚本编写和捕获输出时,在后台使用&符(&)在背景中派生命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在bash脚本中捕获输出的同时在后台派生一个进程.

I wish to fork a process in background, while capturing output in a bash script.

我可以运行以下脚本来ping IP列表,它将每个呼叫移至后台,并且运行速度非常快.但是它没有捕获执行命令以进行进一步处理的输出.

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

我希望在命令中运行带有&符的这种形式的脚本以在后台进行每次ping操作,但是与上面的脚本相比,它运行得非常慢,这表明该脚本不是并行执行的./p>在$(cat list.txt)中用于i的

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

谢谢约翰

推荐答案

以下脚本似乎很慢,因为您试图在循环中回显变量.因此,仅当所有分叉的过程完成时,最后一个回声才会完成,从本质上讲,它是顺序的.

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

此函数与第一个函数一样快,并且您的标准输出位于数组y中.

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

这篇关于Bash脚本编写和捕获输出时,在后台使用&符(&)在背景中派生命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆