“tail”命令的“-f”参数如何工作?

its*_*_me 64 command-line monitoring tail

$ tail -f testfile
Run Code Online (Sandbox Code Playgroud)

该命令应该实时显示指定文件中的最新条目,对吗?但事实并非如此。请纠正我,如果我打算做的事情是错误的......

我创建了一个新文件“aaa”并添加了一行文本并将其关闭。然后发出这个命令(第一行):

$ tail -f aaa
xxx
xxa
axx
Run Code Online (Sandbox Code Playgroud)

最后三行是文件aaa的内容。现在命令仍在运行(因为我使用了-f),我通过 GUI 打开文件 aaa 并开始手动添加更多行。但是终端不显示文件中添加的新行。

这里有什么问题?tail -f如果新条目仅由系统写入,该命令仅显示新条目?(如日志文件等)

Ign*_*ams 69

tail(1) 手册页

   With  --follow  (-f),  tail  defaults to following the file descriptor,
   which means that even if a tail’ed file is renamed, tail will  continue
   to  track  its  end.   This  default behavior is not desirable when you
   really want to track the actual name of the file, not the file descrip-
   tor (e.g., log rotation).  Use --follow=name in that case.  That causes
   tail to track the named file  in  a  way  that  accommodates  renaming,
   removal and creation.
Run Code Online (Sandbox Code Playgroud)

您的文本编辑器正在重命名或删除原始文件并将新文件保存在相同的文件名下。使用-F来代替。

  • *如果*这是您的预期行为。* 可能* 在某些情况下,您希望跟随描述符而不是文件名,但公平地说,我没有遇到过很多这样的情况。 (18认同)

Sté*_*nez 11

您的编辑器有自己的文件缓冲区。当您在编辑器中修改文本时,文件本身不会写入任何内容。

当您保存更改时,编辑器可能只是删除旧文件并创建一个新文件。tail -f仍将连接到已删除的文件,因此不会显示任何新内容。


Ruf*_*ufo 5

tail 默认情况下每 1 秒“刷新”一次,而不是实时。

试试这个(你需要 bash4):

  • 打开2个终端。
  • 在第一个终端执行touch ~/output.txttail -f ~/output.txt
  • 在第二个终端执行 for i in {0..100}; do sleep 2; echo $i >> ~/output.txt ; done
  • 查看第一个终端中tail的输出。

  • @Juan:如今,在 linux 上,`tailf` 有一个基于 inotify 的实现。所以它会实时刷新。 (5认同)
  • 是的,紧随其后的是 `tail`,现在也正在使用 inotify。`tailf` 根本不轮询,只是在文件上没有活动时休眠。`tail -f` 显示一些活动(参见 `strace` 输出)。 (3认同)