且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我不能通过管道多次过滤尾部的输出?

更新时间:2023-11-14 12:53:52

这是一个缓冲问题 - 第一个grep缓冲它输出到管道到另一个命令,但不是如果它打印到标准输出。有关其他信息,请参阅 http://mywiki.wooledge.org/BashFAQ/009


Unexpectedly, this fails (no output; tried in sh, zsh, bash):

echo "foo\nplayed\nbar" > /tmp/t && tail -f /tmp/t | grep played | sed 's#pl#st#g'

Note that two times grep also fails, indicating that it's quite irrelevant which commands are used:

# echo -e "foo\nplayed\nbar" > /tmp/t && tail -f /tmp/t | grep played | grep played

grep alone works:

# echo -e "foo\nplayed\nbar" > /tmp/t && tail -f /tmp/t | grep played
played

sed alone works:

# echo -e "foo\nplayed\nbar" > /tmp/t && tail -f /tmp/t | sed 's#pl#st#g'`
foo
stayed
bar

With cat instead of tail, it works:

# echo -e "foo\nplayed\nbar" > /tmp/t && cat /tmp/t | grep played | sed 's#pl#st#g'
stayed

With journalctl --follow, it fails just like with tail.

What's the reason for being unable to pipe twice?

It's a buffering issue - the first grep buffers it's output when it's piping to another command but not if it's printing to stdout. See http://mywiki.wooledge.org/BashFAQ/009 for additional info.