简体   繁体   English

Bash tail命令和多个管道

[英]Bash tail command and multiple pipes

I am currently facing a problem with the command 我目前面临命令问题

while sleep 0.3; do echo "1"; done | tail -n +3 | grep --line-buffered "1"

I wanted an output that looks like: 我想要一个看起来像这样的输出:

[nothing during 0.6s]
1
1
...

but had: 但有:

[nothing forever]

I found this question and read this blog post but as the --line-buffered option is set for grep , I think this is not a buffering problem. 我发现了这个问题并阅读了这篇博客文章,但是为grep设置了--line-buffered选项,我认为这不是缓冲问题。 My researches did not led me to other solutions, I hope I did not miss something obvious. 我的研究没有让我得到其他解决方案,我希望我没有错过任何明显的东西。

I am using zsh 5.7.1 (x86_64-pc-linux-gnu) if it is important. 我正在使用zsh 5.7.1 (x86_64-pc-linux-gnu)如果它很重要的话。

As Barmar mentioned in the comments, this is getting swallowed up in a 4KB stdio buffer . 正如Barmar在评论中提到的那样,这会被4KB stdio缓冲区吞没。 You can use unbuffer -p to avoid it: 您可以使用unbuffer -p来避免它:

while sleep 0.3; do echo "1"; done | unbuffer -p tail -n +3 | grep 1

Or you could also use stdbuf in line-buffering mode: 或者你也可以stdbuf缓冲模式下使用stdbuf

while sleep 0.3; do echo "1"; done | stdbuf -oL tail -n +3 | grep 1

Depending on the actual situation, you might be able to avoid the problem (caused by the pipe from tail to grep ) by doing everything with a single more powerful tool, like awk : 根据实际情况,您可以通过使用一个更强大的工具(如awk )执行所有操作来避免问题(由管道从tailgrep ):

while sleep 0.3; do echo "1"; done | awk 'NR > 2 && /1/'

But of course, if you need to pipe the output from awk into something else, you just have the same problem all over again. 但是,当然,如果你需要将awk的输出传输到其他东西,你只会再次遇到同样的问题。 But if your version of awk supports it, you can explicitly flush output: 但是如果您的awk版本支持它,您可以显式刷新输出:

while sleep 0.3; do echo "1"; done | awk 'NR > 2 && /1/ {print $0; fflush()}' | | while read x; do echo "read '$x'"; done

...or presumably use unbuffer -p or stdbuf -oL on awk (see @JeffBowman's answer), if you have those (I don't, so I can't test them). ...或者假设在awk上使用unbuffer -pstdbuf -oL (参见@ JeffBowman的答案),如果你有那些(我没有,所以我无法测试它们)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM