Linux logo

What is Linux tail command?

The tail command displays the last part (10 lines by default) of one or more files or piped data. It can be also utilized to track the file changes in real-time.

Among the most frequent uses of the tail command is to watch and examine logs and other files that change over time, usually along with other tools such as grep.

In this tutorial, we’ll discuss the principles of the tail command by using some easy to comprehend examples.

Difference between the tail and head commands?

As their names indicate, the head command will output the first part of the document, whereas the tail command will print the final portion of the file. Both commands write the result to standard output.

Syntax for using Linux tail command

$ tail [OPTION]… [FILE1]..[FILE2]…

An example of the tail command

Basic usage is extremely easy – all you need to do is to pass the name of the file. For example:

$ tail file1

This will display the last ten lines of the specified file. The ten lines is the default.

How To Display a Particular Number of Lines

Use the -n (–lines) option to specify the number of lines to display:

$ tail -n <NUMBER> filename.txt

You may also omit the letter -n and use only the hyphen (-) and the number (without a space between them).

To display the last 20 lines of a file named test.txt you’d use:

$ tail -n 20 test.txt
How to Display a Particular Number of Bytes

To show a particular number of bytes use the -c (–bytes) option.

$ tail -c <NUMBER> filename.txt

For example to display the last 120 bytes of data in the file named test.txt you’d use:

$ tail -c 120 test.txt
Multiple files illustration

We can open a number of files from last simultaneously by executing the tail command. To display the multiple documents, provide the file names as input. It will display the last ten lines of files that are specified.

$ tail -n <number of lines> <file1> <file2> <file3>

For example:

$ tail test1.txt test2.txt

For the last 20 lines for each file:

$ tail -n 20 test1.txt test2.txt
Track a file for changes

To monitor a file for modifications, the ‘-f’ option is used. Here, the ‘-f’ stands for the next. It’s helpful for monitoring log files. Execute the below command:

$ tail -f test.txt

The above command will track the document test.txt’. To exit from tracking, press the “CTRL+C” keys.

Using the head and the tail together example

As mentioned earlier, the head command can give us the first part of a document, while the tail command can output the final part of the input file. But what if we would like to find some part in the midst of a file?

To fix this issue, we can combine the two simple commands.

Let us say we want to get in the 21st to the 26th line from an input file:

$ tail -n +21 test.txt | head -n 5