Tail command displays the last lines from given file. By default, it prints last 10 lines if number of lines is not specified. This command is commonly used to monitor the files changes in real time. In this tutorial, you will learn how to use the Tail command in Linux.
You should have logged in with non-root user account with sudo privileges.
Before go ahead we will see basic syntax for use.
tail [OPTION]… [FILE]…
- OPTION – You can pass option along with command, Get list of options here.
- FILE – Here you can pass one or more file names.
Use the Tail Command
When no option will given with tail command then by default it will print last 10 lines. Run the below command to print default last 10 lines:
How to Display Specific Number of Lines
If you wants to display specified number of lines then you can give -n option with tail command. Following is the basic syntax to print specific number lines.
tail -n test.txt
In above syntax, you have to replace number of lines at . For example, if you want to print 20 lines then you should issue command as below:
tail -n 20 test.txt
Display Specific Number of Bytes
To display specified number of bytes you can use -c option along with tail command.
For example, if you want to display last 512 bytes from the file test.txt then you should run command as:
tail -c 512 test.txt
Also, you can use a multiplier suffix after the number to specify the number of bytes to be shown. Below command will display the last 1KB of the file test.txt:
tail -c 1k test.txt
Display Multiple Files
You can see last 10 lines from multiple files using below command.
tail test1.txt test2.txt
Above command will print last 10 lines of file test1.txt and test2.txt
If you want to see last 25 lines of multiple files then you should issue command as below:
tail -n 20 test1.txt test2.txt
Watch a File for Changes
You can monitor a file for changes by passing the -f (follow) option along with tail command:
tail -f test.txt
This option is mostly useful for monitoring log files. For example, to display the last 10 lines of the /var/log/nginx/error.log file, and monitor the file for updates you would use:
tail -f /var/log/nginx/error.log
You can interrupt the this command by pressing Ctrl + C.
Use Tail Command With Another Commands
You can use this command along with pipe with as a combination.
Below command is used to print last 512 bytes from test.txt to new.txt file:
cat test.txt | tail -c 512 > new.txt
Use following command to print last 10 lines of file test.txt sorted in reverse order:
tail -n 10 test.txt | sort -r
You have learned how to use the tail command in Linux. If you have any questions or suggestion you can leave comment below.