Using the tail command in Linux is straightforward. Here’s a step-by-step guide on how to use it effectively:
Basic Usage
-
Display the Last 10 Lines of a File
By default,tailshows the last 10 lines of a specified file.tail filename.txt -
Display a Specific Number of Lines
You can specify the number of lines you want to see using the-noption.tail -n 5 filename.txtThis command will display the last 5 lines of
filename.txt. -
Follow a File in Real-Time
To monitor a file as it grows (e.g., a log file), use the-foption.tail -f logfile.logThis will keep the file open and display new lines as they are added.
-
Display the Last N Bytes of a File
If you want to see the last few bytes instead of lines, use the-coption.tail -c 50 filename.txtThis command will show the last 50 bytes of
filename.txt.
Advanced Usage
-
Monitor Multiple Files
You can monitor multiple files at once. By default,tailwill show the last 10 lines of each file.tail file1.txt file2.txt -
Suppress Headers for Multiple Files
If you want to suppress the output of headers when monitoring multiple files, use the-qoption.tail -q file1.txt file2.txt -
Use with Process ID
To stop monitoring a file when a specific process ends, use the--pidoption with-f.tail -f --pid=1234 logfile.log -
Follow a Rotating Log File
To keep following a log file even if it gets rotated (deleted and recreated), use the-Foption.tail -F logfile.log
Example Scenario
If you are troubleshooting a web application and want to see the latest access logs, you might run:
tail -f /var/log/apache2/access.log
This command will show you new entries in real-time as users access your site.
Conclusion
The tail command is a versatile tool for viewing the end of files and monitoring changes. Experiment with the options to find the best fit for your needs. If you have any further questions or need more examples, feel free to ask!
