The tail command in unix or linux system is used to print the last N lines from the file on the terminal. Tail command is especially used with log files to read the last few lines to know about the error messages. The syntax of tail command is
tail [options] [files]
The tail command options are:
- c : Prints the last N bytes of file; With leading +, prints the characters from the N byte in the file.
- n : Prints last N lines; With leading + prints lines from the Nth line in the file.
- f : Prints the appended lines on the terminal as the file grows.
Tail Command Examples
Create the following file in your linux or unix operating system for practising the examples:
# cat example.txt virtual storage oracle virtual instance mysql backup dedicated hosting server cloud servers
1. Display last 10 lines
By default, the tail command prints the last 10 lines from the file.
# tail example.txt
2. Display last N lines
Use the -n option to print the last n lines from the file. The following example prints the last 2 lines from the file:
# tail -n2 example.txt dedicated hosting server cloud servers
3. Print lines from the Nth line
You can print lines starting from the Nth line in a file. The following example prints lines from the 2nd line.
# tail -n+2 example.txt oracle virtual instance mysql backup dedicated hosting server cloud servers
4. Print the last n bytes
use the -c option to print the last N bytes from the file. The following example prints the last 8 bytes from the file.
# tail -c8 example.txt servers
5. Print characters from the Nth byte
Use the leading "+" with -c option to print the characters from the Nth byte. The following example prints the characters from the 79th byte.
# tail -c+79 example.txt cloud servers
6. Print last lines from dynamically changing file
The -f option print the lines from file that is growing dynamically. When you run the tail -f filename command, it prints the last 10 lines and waits for new lines to be added to the file. Whenever the new lines are appended to the file, the tail command also appends the new lines on the standard output. The -f option is useful when debugging applications. In general, the applications writes error messages to log files. You can use the -f option to check for the error messages as and when they appear in the log file.
# tail -f logfile