Bash实时读取STDOUT流 [英] Bash reading STDOUT stream in real-time

查看:227
本文介绍了Bash实时读取STDOUT流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经进行了搜索,希望找到数百种解决方案,但没有找到!

I have searched for this and expected to find hundreds of solutions yet found none !

我想读取STDOUT流并等待特定字符串出现,而无需等待过程完成.

I would like to read the STDOUT stream and wait for a specific string to appear, without waiting for the process to finish.

我现在所拥有的,在返回输出之前等待过程完成:

What I have now, waits for the process to finish before returning the output:

RESP=$(execute some command 2>&1)
if $RESP contains something then do something;

我如何实时读取流而不是等待流完成?

How can I read the stream in real-time rather than waiting for it to complete ?

我尝试了paddy建议的以下命令,这些命令可通过ping命令进行测试:

I tried the following suggested by paddy which for testing works with the ping command:

RESP=$(ping 192.168.0.1 | grep seq=5 -m1)

但是它不适用于我要使用dhcpcd的命令:

However it does not work with the command I want to use dhcpcd:

RESP=$(dhcpcd wlan0 -r 192.168.0.190 | grep claims -m1)

与ping测试不同,命令的输出发送到控制台而不是被隐藏,并且即使输出中存在声明"文本,也不会检测到?

Unlike the ping test, the output from the command is sent to the console instead of being hidden, and it never detects the "claims" text even though it is present in the output ?

推荐答案

您可以通过管道插入grep进行匹配,并在遇到匹配项时退出.这也将退出产生输出的程序.

You can pipe into grep to do the matching and have it exit when it encounters a match. That will also exit the program producing the output.

if mycommand | grep something -q; then
    dosomething
fi

如果有任何匹配项(-q),以上内容将退出,但不显示结果.如果要查看输出,可以在第一个匹配项上退出(使用-m1):

The above will quit if anything matches (-q), but not display the result. If you want to see the output, you can quit on the first match (using -m1):

RESP=$(mycommand | grep something -m1)

有关更多信息,请阅读grep的手册页.

Read the man-pages for grep for more information.

如果您不想取消产生输出的程序,则可以尝试将其写入后台文件,然后tail该文件:

If you don't want to cancel the program producing the output, you could try writing it to file in the background, then tail that file:

mycommand > output &
if tail -f output | grep something -q; then
    dosomething
fi

这篇关于Bash实时读取STDOUT流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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