tail Command in Linux

Back

tail command prints the last N number of lines from given input. By default, it prints last 10 lines of each given file.

Syntax and Options

tail [OPTIONS]… [FILE]…

1. Print the last N lines
To view the last N number of lines from file, just pass the file name with -n option as shown below.

$ tail -n 5 flavours.txt
Debian
Redhat
Gentoo
Fedora core
Note: When you simply pass the filename, it prints out the last 10 lines of the file.

2. Print the appended lines as and when the file grows
You can use -f option to output the appended lines of file instantly as shown below,

$ tail -f /var/log/messages
Note: This is very useful to monitor the log files.

3. Terminate the tail command once PID dies
Using –pid with -f option, you can terminate the tail command when the specific process gets over or killed as shown below.

$ tail -f /tmp/debug.log --pid=2575
In the above tail gets terminated immediately when the pid 2575 vanishes.

4. Keep on trying to tail the file even if it is non-existent
Sometimes, the file intended to tail may not be available when you run the tail command and it may get created later or the files becomes inaccessible . 
By this time, you can use the –retry option to keep on trying to open the file as shown below.

$ tail -f /tmp/debug.log --retry
     ?? tail: warning: --retry is useful mainly when following by name
tail: cannot open `/tmp/log' for reading: No such file or directory ??

After giving the above warnings, it is trying to open the file.