简体   繁体   English

使用 tail -F 查看实时更改的文件

[英]Using tail -F to see a file changing in real-time

I have a script that collects the size of a file that is being constantly fed.我有一个脚本,用于收集不断输入的文件的大小。 I'm echoing its size to a log file (echo 'filesize is $size' > log.txt) so I only have the last size information.我将其大小回显到日志文件(echo 'filesize is $size' > log.txt),所以我只有最后的大小信息。 So, only one line.所以,只有一行。

Now, in another terminal, I wanted to tail that log file to see its size increasing in real time.现在,在另一个终端中,我想拖尾该日志文件以查看其大小实时增加。 It turns out, tail -f path/to/file gives me the output I want but it keeps jumping to the next line (as expected, I guess).事实证明, tail -f path/to/file 给了我想要的输出,但它一直跳到下一行(我猜是预期的)。

So, the output is something like:所以,输出是这样的:

$ tail -F log.txt 2>/dev/null
filesize is 1.658 GB
filesize is 1.659 GB
filesize is 1.659 GB
filesize is 1.660 GB

I wanted something more like the command "less" in which you don't have the cursor back.我想要更像命令“less”的东西,你没有光标回来。 Maybe a better example would be "mtr", that keeps updating the information on the screen without going to next line (as opposed to traceroute).也许一个更好的例子是“mtr”,它不断更新屏幕上的信息而不去下一行(与traceroute相反)。

Thank you,谢谢,

使用此命令。

watch tail -n 1 log.txt
while [ 1 ]; do sleep 1; clear; tail log.txt; done

这没有传递命令和参数来watch的缺点(有时你需要跳额外的循环才能正确),并且它会清除终端。

您可以watch命令以每n秒监视文件更改/差异( -d

watch -n 5 -d cat log.txt

The fanciest solution to receive realtime information on a file ist to use inotify接收有关文件的实时信息的最佳解决方案是使用 inotify

Which is a linux kernel feature to receive notification when a specific file changes.这是一个 linux 内核功能,用于在特定文件更改时接收通知。 You can either write your own c program which uses the functionality or you simply build a script with the inotify-wait or inotify-watch command.您可以编写自己的使用该功能的 c 程序,也可以简单地使用 inotify-wait 或 inotify-watch 命令构建脚本。 You probably need to install it though.不过,您可能需要安装它。 But both are well documented.但两者都有很好的记录。 New versions of tail also use this linux kernel functionality新版本的 tail 也使用了这个 linux 内核功能

EDIT: keep in mind that this only helps you with monitoring file events.编辑:请记住,这只会帮助您监视文件事件。 What you do when such an event occours is not my cup of tea.当这样的事件发生时你所做的不是我的那杯茶。

PS.附注。 Have you considered that the process that writes the file MAYBE only flushes its writing buffer when a line break is present您是否考虑过写入文件的进程可能仅在出现换行符时才刷新其写入缓冲区

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM