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 ~]#