For the purpose of troubleshooting, one of the most useful commands you will use is known as tail. A command-line expression that can be used to read the last lines of a log file is as follows:
# tail -n 100 /var/log/maillog
Similarly, tail can also be used to obtain the most recently added lines like this:
# tail -f /var/log/maillog
Syntax
The syntax of the tail commands is:
$ tail [options] {file names}
tail Command Options
The following are some common options used with the tail command:
- -f – dynamically watch a file (the output will automatically update when the file changes).
- -n {number} — show the specified number of lines, rather than the default of 10.
If you encounter below error while running the tail command:
tail: command not found
you may try installing the below package as per your choice of distribution:
Distribution | Command |
---|---|
OS X | brew install coreutils |
Debian | apt-get install coreutils |
Ubuntu | apt-get install coreutils |
Alpine | apk add coreutils |
Arch Linux | pacman -S coreutils |
Kali Linux | apt-get install coreutils |
CentOS | yum install coreutils |
Fedora | dnf install coreutils |
Raspbian | apt-get install coreutils |
tail Command Examples
1. Print the last two blocks of bigfile:
$ tail −2b bigfile
2. Show last ‘count’ lines in file:
$ tail --lines count path/to/file
3. Print a file from a specific line number:
$ tail --lines +count path/to/file
4. Print a specific count of bytes from the end of a given file:
$ tail --bytes count path/to/file
5. Print the last lines of a given file and keep reading file until `Ctrl + C`:
$ tail --follow path/to/file
6. Keep reading file until `Ctrl + C`, even if the file is inaccessible:
$ tail --retry --follow path/to/file
7. Show last ‘num’ lines in ‘file’ and refresh every ‘n’ seconds:
$ tail --lines count --sleep-interval seconds --follow path/to/file
Conclusion
The tail command is more useful when we are troubleshooting issues using log files. It enables us to see the most recent lines of output by continuously displaying the addition of any new lines in the log file as soon as they appear. Thus, it enables us to monitor any current activity that is being reported or recorded.