---
title: "我使用过的Linux命令之tail - 输出文件尾部/动态监视文件尾部"
author: "codingstandards"
date: "2010-12-03T14:39:57Z"
tags: ["C#", "F#", "Linux", "Tomcat", "log4j"]
categories: ["操作系统"]
slug: "linux-tail"
draft: false
lastmod: "2010-12-03T14:41:04Z"
id: 832575
url: "https://codingstandards.iteye.com/blog/832575"
---

# 我使用过的Linux命令之tail - 输出文件尾部/动态监视文件尾部

本文链接：[http://codingstandards.iteye.com/blog/832575](/blog/832575)   （转载请注明链接）

## 用途说明

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就不能动态输出新的日志内容了。tail命令本身提供了很多参数，似乎都不能完美的解决这个问题。最后只好编写了一个脚本ftail.sh来跟踪日志，详见《[Linux下实时跟踪log4j日志文件的bash脚本 - 增强了tail -f的功能](/blog/803686) 》。**刚才我仔细查看了tail的手册页，发现tail -F就能够做到跟踪这种类型的日志。转念一想，这种需求应该早就被Linux世界的人给满足了的。**

 

格式：tail -F file

格式：tail --follow=name --retry file

功能与tail -f file相同，也是动态跟踪文件的变化，不同的是执行此命令时文件可以不存在。

 

以上处理都是针对文本文件的，下面是针对二进制文件的情形。

 

格式：tail -c *n* file

取文件file的最后n个字节。

 

格式：tail -c +*n* file

取文件file的第n个字节后的内容。从1开始计数。

## 使用示例

### 示例一 输出文件尾部

**先使用seq命令输出20个数字保存到1.txt，然后尝试使用tail命令。**

\[root@new55 ~]# seq 20 &gt;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 ~]#

 

### 示例二 动态跟踪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)  
2010-12-03 13:23:02,236 \[http-80-15] DEBUG mhr.roi.MhrManager - MhrGetJobReq={seq=991,job\_id='86130469-0006'}  
2010-12-03 13:23:02,301 \[http-80-15] DEBUG mhr.roi.MhrManager - MhrGetJobRsp={seq=991,result=0(成功),,info={job\_id='86130469-0006',employer\_id=86130469,employer\_name=无锡富士时装有限公司,,,job\_title='|570309|',job\_title0='文员',job\_type=f(全职),issue\_time='2010-11-03 00:00:00.0',work\_address='1902',work\_address0=无锡市,desired\_count='1',,,,,,job\_desc=大专，1年以上5s管理工作经验，电脑操作熟练。,required\_experience=1(一年以上),,,,required\_degree=15(大专),,,,,,,valid\_days=30,access\_count=12,expire\_time='2010-12-03 00:00:00.0',job\_status=1(过期),,,,,,contact\_name=王小姐,contact\_number=0510-85550088,remarks='★此职位是从后台导入的  
',enter\_time='2010-11-03 09:45:11.0',change\_time=2010-12-03 02:18:05.0,,job\_seq=123201,,required\_min\_age=22,,,accommodations=面议,serve\_principal=wjw12580,job\_summary=大专，1年以上5s管理工作经验，电脑操作熟练,,}}  
2010-12-03 13:23:02,302 \[http-80-15] DEBUG mhr.roi.MhrManager - MhrGetEmployerReq={seq=0,employer\_id='86130469'}  
2010-12-03 13:23:02,304 \[http-80-15] DEBUG mhr.roi.MhrManager - MhrGetEmployerRsp={seq=0,result=0(成功),,info={employer\_id='86130469',employer\_name=无锡富士时装有限公司,employer\_region=1902,employer\_address=无锡市滨湖镇山水城科技园8号,,employer\_desc=无锡富士时装(集团)有限公司成立于1992年，是中日韩合资企业。主要生产高档针织时装，产品全部外销，连续多年荣获“中国行业500强”、“全国工业重点行业效益十佳企业”、“无锡市百佳企业”等称号。公司总部位于江苏省无锡市滨湖镇山水城科技园，全新的厂房设施，占地面积30亩。公司分别在苏州、泰兴、盐城、徐州设有分厂，集团公司现有职工1500多人，年销售额近3亿元。,,,,,,open\_mode=5(系统自动操作),open\_time='2010-11-03 09:45:10.0',,,,,contact\_name=王小姐,contact\_number=0510-85550088,,,,,employer\_status=1(已经开通),,,login\_password=871386,,agency=false,balance=100.0000,,,,,serve\_principal=wjw12580,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,remarks='此帐号由“12580zgz-盐城维克多网络传媒有限公司”导入',enter\_time='2010-11-03 09:45:10.0',}}  
Ctrl+C  
\[root@web logs]#

 

### 示例三 动态跟踪log4j日志

**经过我的试验，发现tail -F功能的强大，它等同于--follow=name --retry。如果你跟踪的文件被移动或者改名后, 你还想继续tail它, 你可以使用这个选项。**

**tail手册页中关于--retry的说明：keep trying to open a file even if it is inaccessible when tail starts or  if  it  becomes  inaccessible later; useful when following by name, i.e., with --follow=name。** **tail命令开始执行时文件不存在或者执行过程中文件不能访问，会不断重试。**

**关于--follow的说明：-f, --follow\[={name|descriptor}] output appended data as the file grows; -f, --follow, and --follow=descriptor are equivalent** 。**--follow=descriptor表明跟踪的是文件描述符，  --follow=name表明跟踪的是文件名称。 如果文件名称改掉之后，还想继续跟踪原文件名称对应的尾部内容，就得使用-F选项而不是-f选项了。**

\[root@web imx\_server]# tail -F log/IMX.LOG  
14:13:28.892  INFO ImxConnection\[6] imx.server.ImxConnection - RX IMX\_ACTIVE\_TEST{seq=3460,client\_id=1291343201649042,presence\_status=1(presence\_status\_online),}  
14:13:28.892 DEBUG ImxConnection\[6] org.logicalcobwebs.proxool.ImxDB - 006417 (01/02/00) - Connection #9 served  
14:13:28.892  INFO ImxConnection\[6] imx.dbo.ImxOnlineInfoRow - EXEC SQL UPDATE imx\_online\_info SET last\_active\_time = '2010-12-03 14:13:28.0' WHERE account = 'zhy'  
14:13:28.894 DEBUG ImxConnection\[6] org.logicalcobwebs.proxool.ImxDB - UPDATE imx\_online\_info SET last\_active\_time = '2010-12-03 14:13:28.0' WHERE account = 'zhy';  (1 milliseconds)  
14:13:28.894 DEBUG ImxConnection\[6] org.logicalcobwebs.proxool.ImxDB - 006417 (00/02/00) - Connection #9 returned (now AVAILABLE)  
14:13:29.625  INFO ImxConnection\[6] imx.server.ImxConnection - RX IMX\_ACTIVE\_TEST{seq=3461,client\_id=1291343201649042,presence\_status=1(presence\_status\_online),}  
14:13:29.626 DEBUG ImxConnection\[6] org.logicalcobwebs.proxool.ImxDB - 006418 (01/02/00) - Connection #8 served  
14:13:29.626  INFO ImxConnection\[6] imx.dbo.ImxOnlineInfoRow - EXEC SQL UPDATE imx\_online\_info SET last\_active\_time = '2010-12-03 14:13:29.0' WHERE account = 'zhy'  
14:13:29.627 DEBUG ImxConnection\[6] org.logicalcobwebs.proxool.ImxDB - UPDATE imx\_online\_info SET last\_active\_time = '2010-12-03 14:13:29.0' WHERE account = 'zhy';  (0 milliseconds)  
14:13:29.653 DEBUG ImxConnection\[6] org.logicalcobwebs.proxool.ImxDB - 006418 (00/02/00) - Connection #8 returned (now AVAILABLE)  
Ctrl+C  
\[root@web imx\_server]#

 

**总结一下：要想跟踪会更名的日志的话，用tail -F而不是tail -f。**

 

### 示例四 处理二进制文件

\[root@new55 ~]# seq 20 &gt;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 ~]# hexdump -C 1.txt  
00000000  31 0a 32 0a 33 0a 34 0a  35 0a 36 0a 37 0a 38 0a  |1.2.3.4.5.6.7.8.|  
00000010  39 0a 31 30 0a 31 31 0a  31 32 0a 31 33 0a 31 34  |9.10.11.12.13.14|  
00000020  0a 31 35 0a 31 36 0a 31  37 0a 31 38 0a 31 39 0a  |.15.16.17.18.19.|  
00000030  32 30 0a                                          |20.|  
00000033  
\[root@new55 ~]# tail -c 10 1.txt | hexdump -C  
00000000  0a 31 38 0a 31 39 0a 32  30 0a                    |.18.19.20.|  
0000000a  
\[root@new55 ~]# tail -c -10 1.txt | hexdump -C  
00000000  0a 31 38 0a 31 39 0a 32  30 0a                    |.18.19.20.|  
0000000a  
\[root@new55 ~]# tail -c +10 1.txt | hexdump -C  
00000000  0a 36 0a 37 0a 38 0a 39  0a 31 30 0a 31 31 0a 31  |.6.7.8.9.10.11.1|  
00000010  32 0a 31 33 0a 31 34 0a  31 35 0a 31 36 0a 31 37  |2.13.14.15.16.17|  
00000020  0a 31 38 0a 31 39 0a 32  30 0a                    |.18.19.20.|  
0000002a  
\[root@new55 ~]#

 

## 问题思考

## 相关资料

【1】Linux宝库  [head,tail,sed](http://www.linuxpk.com/168.html)    
【2】Tai的日记  [tail -f 和 -F 的用法](http://www.douban.com/note/85851188/)    
【3】CSDN论坛  [tail -f run.log 导致 tail: run.log: file truncated](http://topic.csdn.net/u/20080201/09/2f55ff69-96f9-4960-a6d5-14aa2585dafe.html)      
【4】短裤党    [tail -f 退出不了?](http://gundumw100.iteye.com/blog/506457)       
【5】新课网    [linux下tail命令创建自解压tar文件教程](http://www.xker.com/page/e2009/0804/75000.html)

 

返回 [我使用过的Linux命令系列总目录](/blog/786653)