When troubleshooting a server or monitoring a background process in Linux, opening a massive log file in a text editor like `nano` or `vim` is incredibly inefficient. If the file is constantly updating, you will not see the new data without manually reloading. The solution is the tail command, a fundamental Linux utility designed to output the last part of a file.
What is the tail Command?
By default, the tail command reads a file and prints the very last 10 lines to the terminal standard output. This is highly useful for checking the most recent entries in system logs (like /var/log/syslog or /var/log/auth.log) without scrolling through thousands of historical lines.
Basic Usage and Changing Line Counts
To view the last 10 lines of an Apache error log, you would simply type:
tail /var/log/apache2/error.log
If 10 lines are not enough to give you context, you can use the -n (number) flag to specify exactly how many lines you want to see. To print the last 50 lines:
tail -n 50 /var/log/apache2/error.log
Monitoring Files in Real-Time with the -f Flag
The true power of the tail command comes from the -f (follow) flag. When you use this flag, tail does not exit after printing the final lines. Instead, it remains open and actively monitors the file for changes. Whenever a new line is written to the file by a background process, tail instantly prints it to your terminal screen.
tail -f /var/log/nginx/access.log
This creates a live, scrolling feed of your web server’s traffic. It is an indispensable tool for watching logs while you trigger an action (like logging into a website or restarting a service) to immediately see the resulting output. To exit the live follow mode and return to your command prompt, press Ctrl + C.
Handling Rotated Logs with -F
Linux systems frequently use a utility called logrotate to prevent log files from growing infinitely large. When a file gets too big, it is renamed (e.g., syslog.1) and a brand new empty file (syslog) is created in its place.
If you are monitoring a file with tail -f and the file is rotated, tail will stop updating because it is still watching the old, renamed file descriptor. To solve this, use the uppercase -F flag (or --follow=name --retry). This tells tail to track the actual filename, not the file descriptor. If the file is deleted and recreated, tail will automatically attach to the new file and continue the live feed.
tail -F /var/log/syslog
Monitoring Multiple Files Simultaneously
You are not limited to watching a single file. You can pass multiple file paths to the tail command. It will print the headers for each file to distinguish the output.
tail -f /var/log/syslog /var/log/auth.log
When running in follow mode, anytime either file is updated, the new lines will appear on the screen with the filename printed above them, allowing you to monitor a complex application from a single terminal window.