How do I use `tail`?

0127

Using the tail command in Linux is straightforward. Here’s a step-by-step guide on how to use it effectively:

Basic Usage

  1. Display the Last 10 Lines of a File By default, tail shows the last 10 lines of a specified file.

    tail filename.txt
    
  2. Display a Specific Number of Lines You can specify the number of lines you want to see using the -n option.

    tail -n 5 filename.txt
    

    This command will display the last 5 lines of filename.txt.

  3. Follow a File in Real-Time To monitor a file as it grows (e.g., a log file), use the -f option.

    tail -f logfile.log
    

    This will keep the file open and display new lines as they are added.

  4. Display the Last N Bytes of a File If you want to see the last few bytes instead of lines, use the -c option.

    tail -c 50 filename.txt
    

    This command will show the last 50 bytes of filename.txt.

Advanced Usage

  1. Monitor Multiple Files You can monitor multiple files at once. By default, tail will show the last 10 lines of each file.

    tail file1.txt file2.txt
    
  2. Suppress Headers for Multiple Files If you want to suppress the output of headers when monitoring multiple files, use the -q option.

    tail -q file1.txt file2.txt
    
  3. Use with Process ID To stop monitoring a file when a specific process ends, use the --pid option with -f.

    tail -f --pid=1234 logfile.log
    
  4. Follow a Rotating Log File To keep following a log file even if it gets rotated (deleted and recreated), use the -F option.

    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!

0 Comments

no data
Be the first to share your comment!