开发者

Shell script re-directing output with tee command buffers output in some cases and not in others

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开发者_StackOverflow中文版.

I also wrote a similar script using exec and cat commands and it exhibits the same behavior.


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 use tail -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, and tail 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, and tail 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

tail -n +1 -f pipe
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜