'grep -q' 不以 'tail -f' 退出 [英] 'grep -q' not exiting with 'tail -f'
问题描述
我正在尝试实现一个脚本来等待日志文件中的特定消息.记录消息后,我想继续脚本.
I am trying to implement a script that wait for a specific message in a log file. Once the message is logged then I want to continue the script.
这是我尝试使用 tail -f
和 grep -q
的内容:
Here's what I am trying out with tail -f
and grep -q
:
# tail -f logfile | grep -q 'Message to continue'
grep
永远不会退出,因此即使文件中记录了继续消息",它也会永远等待.
The grep
never quit and so it waits forever even if 'Message to continue' is logged in the file.
当我在没有 -f
的情况下运行它时,它似乎工作正常.
When I run this without -f
it seems to work fine.
推荐答案
tail -f
将读取文件并显示稍后添加的行,它不会终止(除非像 SIGTERM 这样的信号
发送).grep
不是这里的阻塞部分, tail -f
是.grep
会从管道中读取数据,直到管道关闭,但这永远不会是因为 tail -f
不会退出并保持管道打开.
tail -f
will read a file and display lines later added, it will not terminate (unless a signal like SIGTERM
is sent). grep
is not the blocking part here, tail -f
is. grep
will read from the pipe until it is closed, but it never is because tail -f
does not quit and keep the pipe open.
您的问题的解决方案可能是(未经测试并且很可能表现不佳):
A solution to your problem would probably be (not tested and very likely to perform badly):
tail -f logfile | while read line; do
echo $line | grep -q 'find me to quit' && break;
done
这篇关于'grep -q' 不以 'tail -f' 退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!