【问题标题】:Piping standard output of tee effects output of its files其文件的 tee 效果输出的管道标准输出
【发布时间】:2013-04-12 04:06:40
【问题描述】:

当我发现一个奇怪的问题时,我遇到了How can I send the stdout of one process to multiple processes using (preferably unnamed) pipes in Unix (or Windows)? 的答案并正在玩grep。以下工作符合我的预期:

$ while [ 1 ]; do sleep 1 ; echo tick; done | tee >(grep -o ti) >(grep -o ic) >(grep tick) >/dev/null
ic
ti
tick
ic
tick
ti
^C

所有三个grep 命令都应用于​​循环的输出。

但是,如果我将 tee 的输出通过管道传输到 grep(而不是将其重定向到 /dev/null),则文件上的 greps 将停止工作:

$ while [ 1 ]; do sleep 1 ; echo tick; done | tee >(grep -o ti) >(grep -o ic) | grep tick
tick
tick
^C

为什么会这样?

【问题讨论】:

    标签: linux bash io-redirection


    【解决方案1】:

    我会冒险猜测......

    tee >(grep -o ti) >(grep -o ic) >(grep tick) >/dev/null
    tee >(grep -o ti) >(grep -o ic) | grep tick
    

    在第一个命令中,参数是从左到右处理的,因此grep -o ti 的输出将转到标准输出,其他两个进程替换也是如此,然后tee 的标准输出被重定向到/dev/null(但进程已经使用原始标准输出启动)。

    在第二个命令中,到grep tick 的管道在shell 处理>(grep -o ti) 之前就已经设置好了,所以grep 的标准输出顺着管道传输。 tiic 行不是由 grep tick 命令选择的。如果您将其更改为 grep i,您可能还会看到 tiic 行。

    我不得不将命令调整为:

    while true; do echo tick; done |
    tee >(grep -o ti) >(grep -o ic) | grep i | grep -v tick
    

    查看tiic 命令。这与使用标准 I/O 进行缓冲有关; grep 命令的输出将进入管道,因此它是完全缓冲的,并且输出分批出现。除非我放弃sleep 1,否则要花很长时间才能看到替代输出。

    查看输出的更好的命令是:

    while true; do echo tick; done |
    tee >(grep -o ti) >(grep -o ic) | grep i | uniq
    

    输出包含如下行:

    ictick
    tick
    ic
    i
    ti
    tick
    ic
    tick
    ti
    ttick
    ic
    itick
    tick
    ic
    i
    ti
    tiic
    ictick
    tick
    

    故事的寓意可能是确保每个流程替换的输出都转到一个已知文件。

    【讨论】:

    • 所以,要明确一点,循环的输出和文件重定向内的两个grep的输出都进入grep tick?
    • 是的,这似乎是正在发生的事情。
    • 是的,我现在看到了。比较while true; do echo tick; done | tee >(grep -o ti) >(grep -o ic) | grep -o tick | uniqwhile true; do echo tick; done | tee >(grep -o ti) >(grep -o ic) | grep tick | uniq 的输出。很有趣,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多