When troubleshooting a Linux server, the answers are almost always found inside the system log files. However, log files (like /var/log/syslog or an Apache web server access log) can contain millions of lines of text.
If you use a standard command like cat to open the file, your terminal will be flooded with an unstoppable wave of historical data that happened months ago. Because errors usually occur now, the only data you actually care about is at the very bottom of the document. To view just the newest entries without loading the entire massive file, you must use the tail command.
The Basic tail Command
By default, the tail command extracts exactly the last 10 lines of a specified file and prints them to your screen.
tail /var/log/auth.log
This command is incredibly fast because it does not read the file from the beginning; it seeks directly to the end, making it safe to run on gigabyte-sized log files.
Changing the Number of Lines
If an application crashed and generated a massive stack trace error, the last 10 lines will not provide enough context. You can instruct tail to display a specific number of lines using the -n (number) flag.
To view the last 50 lines of the file:
tail -n 50 /var/log/apache2/error.log
The Killer Feature: Following a File in Real-Time
The absolute most powerful use case for the tail command is the -f (follow) flag.
When you run tail -f, the command prints the last 10 lines of the file, but it does not stop running. It stays open and actively watches the file. If a new line of text is appended to the file by the operating system, tail instantly prints it to your screen in real-time.
tail -f /var/log/nginx/access.log
This allows you to “watch” the log live. You can open a terminal, run the command above, and then open a web browser to visit your website. As you click around, you will see the web server actively generating log entries and scrolling them down your terminal screen.
When you are finished watching the live feed, you must press Ctrl+C to kill the command and return to your standard terminal prompt.
Tailing Multiple Files Simultaneously
If you are troubleshooting a complex web application, you might need to watch both the standard access log and the error log at the exact same time.
You can pass multiple filenames to the tail command:
tail -f /var/log/nginx/access.log /var/log/nginx/error.log
The command will watch both files simultaneously. When a new line is generated in either file, it will print a small header to your screen indicating which file the new data came from, followed by the actual log entry. This multi-tailing feature is invaluable for correlating web traffic with server errors in real time.