使用 tee 命令重定向输出的 Shell 脚本在某些情况下会缓冲输出,而在其他情况下则不会
我将 shell 脚本简化为两个命令:
终端 A(将 STDIN 重定向到命名管道):
tee -a >>pipe
终端 B(从上面使用的管道读取):
tail -f pipe
结果我不明白:
- 结果 1:开始 tee,开始 tail:第一个终端的任何输入都将被缓冲,并且仅在 tee 命令执行后的第二个终端中显示停止(ctrl-c)。
- 结果2:开始tee,开始尾部,停止tee,再次开始tee:现在只有每一行被缓冲(我想要的结果)。结果显示在终端 2 中终端 1 的每行输入末尾处。
- 结果 3(就其价值而言):先开始 tail,然后再开始 tee:结果相同作为#1。
我还使用 exec 和 cat 命令编写了一个类似的脚本,它表现出相同的行为。
I've simplified a shell script down to two commands:
Terminal A (Redirect STDIN to a named pipe):
tee -a >>pipe
Terminal B (Read from the pipe used above):
tail -f pipe
The results I don't understand:
- Result 1: Start tee, start tail: any input into the first terminal will be buffered and only show up in the 2nd after the tee command is stopped (ctrl-c).
- Result 2: Start tee, start tail, stop tee, start tee again: Now only each line is buffered (the result I want). Results show up in terminal 2 at the end of each line of input into terminal 1.
- Result 3 (for what it's worth): Start tail first, then tee: same result as #1.
I also wrote a similar script using exec and cat commands and it exhibits the same behavior.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不是这方面的专家,但这种行为似乎很简单。
假设您将
tail
应用于普通文本文件;它将打印最后 10 行并退出。如果使用tail -f
,它将打印最后10行,然后监视文件;从那时起,它将打印附加到文件中的每个新行。这就是您正在寻找的行缓冲。现在将
tail -f
应用于命名管道。无论您在另一端输入什么,都就像文件的初始内容一样,tail
耐心地等待末尾,以便它可以打印“最后”10 行。当该进程结束时,它会通过管道发送一个“文件结束”符号(我不知道那是什么,只知道它存在),然后tail
打印并开始监视。如果您随后启动一个或多个写入管道的新进程,tail
会将新行视为新行,并将其打印出来。如果您想缓冲并打印所有行,您可以启动和停止 T 恤来启动泵,或者只使用
I'm not an expert on this, but the behavior seems straightforward.
Suppose you apply
tail
to an ordinary text file; it will print the last 10 lines and quit. If you usetail -f
, it will print the last 10 lines, then monitor the file; from then on it will print each new line that is appended to the file. This is the line buffering you're looking for.Now apply
tail -f
to a named pipe. Whatever you put in the other end is like the initial contents of the file, andtail
waits patiently for the end so that it can print the "last" 10 lines. When that process ends, it sends an "end of file" symbol (I don't know what that is, only that it exists) through the pipe, andtail
prints-- and starts monitoring. If you then start one or more new processes that write to the pipe,tail
takes the new lines as, well, new, and prints them out.If you want to buffer and print all lines, you could start-and-stop tee to prime the pump, or just use