简介
tail 这个命令源自英文单词 “尾巴”,它的主要功能是显示文件的最后几行内容。通过使用 tail,用户可以查看文件的最新添加内容,特别是对于监控日志文件来说非常有用。tail 命令默认显示文件的最后 10 行,但这可以通过参数调整。
使用方式
tail [参数]... [文件]...
常用选项
-
-c, --bytes=[+]NUM:输出每个文件的最后NUM个字节的数据;或者使用-c +NUM来输出从文件NUM个字节开始到结束的所有数据。 -
-f, --follow[={name|descriptor}]:在输出文件内容后继续监听文件的变化,并且在有新数据追加到文件中时输出追加的数据。如果没有为该选项提供参数,则会将参数默认为descriptior。 -
-F:与--follow=name --retry作用相同。 -
-n, --lines=[+]NUM:输出文件的最后NUM行,或使用-n +NUM来从文件的第NUM开始输出。 -
--max-unchanged-stats=N:与--follow=name一起使用时,在指定文件经过N次(默认为 5)检查且其大小未发生变化的情况下重新打开文件,以确保其即使被重命名或删除,tail 仍然可以监视对应新的文件。如果存在inotify机制,则该选项通常不太需要。 -
--pid=PID:与-f选项一起使用可以在指定进程终止时停止tail指令。 -
-q, --quiet, --silent:不要输出文件名。(一般在给定多个文件的情况下tail会在输出文件内容前输出文件名。) -
--retry:在文件不可访问时持续尝试打开。 -
-s, --sleep-interval=N:与-f选项一起使用时,在每次检查文件变化前休眠N秒(默认为 1)。在存在inotify机制且与--pid=P选项同时使用时会每N秒至少检查一次进程P。 -
-v, --verbose:总是输出文件名。 -
-z, --zero-terminated:将NUL字符(\0)(而不是换行符)作为行分隔符。 -
--help:显示帮助信息。 -
--version:显示版本信息。
参考示例
1. 默认显示指定文件尾部的 10 行内容
tail tail.txt
使用 tail + 文件名 可以显示指定文件末尾的 10 行内容:
jay@jaylinuxlenovo:~/test$ tail tail.txt Copyright © 2018 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.SEE ALSOhead(1)Full documentation at: <https://www.gnu.org/software/coreutils/tail>or available locally via: info '(coreutils) tail invocation'GNU coreutils 8.30 September 2019 TAIL(1)
2. 显示指定文件尾部的 5 行内容
tail -n 5 tail.txt
使用 -n 选项可以指定显示的行数:
jay@jaylinuxlenovo:~/test$ tail -n 5 tail.txtFull documentation at: <https://www.gnu.org/software/coreutils/tail>or available locally via: info '(coreutils) tail invocation'GNU coreutils 8.30 September 2019 TAIL(1)
3. 显示指定文件尾部 200 个字符的内容
tail -c 200 tail.txt
使用 -c 选项可以指定输出末尾对应字节数的数据:
jay@jaylinuxlenovo:~/test$ tail -c 200 tail.txt
on'GNU coreutils 8.30 September 2019 TAIL(1)
4. 总是在输出头部显示文件名
tail -v test.txt
使用 -v 选项可以在任何情况下都在输出的头部显示文件名:
jay@jaylinuxlenovo:~/test$ tail -v test.txt
==> test.txt <==
wsssssssssssssddddddssssssssssssssssss
wsssssssssssssddddddsssssssssssssssssssssssssssssssddddddsssssssssssssssss
ssssssssssssssddddddssssssssssssssssss
ssssssssssssssddddddssssssssssssssssssasdasdasdasdasdasdasdassdaasd
5. 实时追踪文件被追加的内容
tail -f test.txt
使用 -f 选项可以使 tail 指令持续检测指定文件,并在其发生变化时输出:

本例使用了两个命令行,一个使用 tail -f 命令监测 test.txt 文件尾部的最新内容,一个使用 echo >> 命令 在 test.txt 尾部追加内容。可以看到每次追加的新内容都会在左边的 tail 监测窗口中显示出来。
注意事项
-
使用
-f跟踪文件时,tail默认会追踪文件描述符,这意味着如果对应的文件进行了重命名,tail也能正常追踪。但这种默认行为对于你真的想追踪文件名而非描述符时(如日志的轮转)是不理想的,此时你需要使用--follow=name,来使tail能够基于文件名来追踪。 -
在处理大文件时,
tail比完整读取文件的命令(如cat)更高效。 -
使用
-f参数监控动态文件时,记得在不需要时使用Ctrl+C来终止命令。 -
选项中的
NUM可以使用乘数后缀,如b对应512,kB对应1000,K 1024,MB 1000*1000,M 1024*1024,GB 1000*1000*1000,G 1024*1024*1024;类似的还有T,P,E,Z,Y。