tail命令可以输出文件的尾部内容,默认情况下它显示文件的最后十行。它常用来动态监视文件的尾部内容的增长情况,比如用来监视日志文件的变化。与tail命令对应的是head命令,用来显示文件头部内容。
常用参数
格式:tail file
输出指定文件file的尾部内容,默认输出最后十行内容(output the last part of files。Print the last 10 lines of each FILE to standard output. )
格式:tail file1 file2 ...
指定多个文件时,会显示每个文件的文件名称,再显示该文件的尾部内容(With more than one FILE, precede each with a header giving the file name.)
格式:tail
格式:tail -
不指定文件时,表明从标准输入读取内容,这通常用在管道线后面,把前一个命令的输出作为tail的输入内容(With no FILE, or when FILE is -, read standard input.)
格式:tail -n file
格式:tail -n n file
格式:tail --lines=n
显示文件最后n 行,比如tail -20 file就是显示文件最后10行,这个参数可以配合其他参数与使用。注意上面三种格式的斜体n 是实际要显示的行数的数值。
注意:tail -n可以显示最后n行的文本内容。那么有没有一种方式显示从n行开始的文本内容,答案是肯定的。
tail -n +4 file表示显示文件file从第4行开始的内容。从1开始计数。
格式:tail -f file
动态跟踪文件file的增长情况(output appended data as the file grows),tail会每隔一秒去检查一下文件是否增加新的内容,如果增加就追加在原来的输出后面显示。但这种情况,必须保证在执行tail命令时,文件已经存在。
如果想终止tail -f的输出,按Ctrl+C中断tail程序即可。如果按Ctrl+C不能中断输出,那么可以在别的终端上执行killall tail强行终止。
注意:采用tail -f来监控文件变化情况时,在某些情况会不太灵。比如在java应用程序中采用log4j日志时,每隔1个小时生成一个新的日志文件,当前的日志输出在LOG4J.LOG中,当一个小时过去后,log4j会将LOG4J.LOG改名成LOG4J.yyyy-mm-dd-HH的形式。那么这个时候tail -f就不能动态输出新的日志内容了
示例二 动态跟踪tomcat输出
动态跟踪tomcat输出。
[root@web logs]# tail -f catalina.out
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
使用示例
示例一 输出文件尾部
先使用seq命令输出20个数字保存到1.txt,然后尝试使用tail命令。
[root@new55 ~]# seq 20 >1.txt
[root@new55 ~]# cat 1.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[root@new55 ~]# tail 1.txt
11
12
13
14
15
16
17
18
19
20
[root@new55 ~]# tail -3 1.txt
18
19
20
[root@new55 ~]# tail -n 3 1.txt
18
19
20
[root@new55 ~]# tail --lines=3 1.txt
18
19
20
[root@new55 ~]# tail -n +14 1.txt
14
15
16
17
18
19
20
[root@new55 ~]#