4 UNIX / Linux tail Command Examples

What is tail?
4 tail examples
Syntax and Options
Related Commands

What is tail?

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


4 tail Examples

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.

Syntax and Options

tail [OPTIONS]… [FILE]…

Short Option Long Option Option Description
-c –bytes to print last N bytes from each input file
-f –follow to print appended data as and when the file grows
-n –lines to print last N lines from each input file
–pid with -f, to terminate after PID dies
-q –silent, –quiet to prevent printing of header information
–retry to keep retrying to open a file even when it is not exist or becomes inaccessible. Useful when it is used with -f
-s –sleep-interval to sleep for N seconds between iterations
-v –verbose to print header information always


Related Commands

head