How to use Linux head and tail commands

When working with large log files or data files on your Linux server, opening the entire file can be slow and inefficient. Instead, the head and tail commands let you quickly view the beginning or end of any file. These simple but powerful tools are essential for anyone managing a Linux hosting account.

Using the head command

The head command shows you the first lines of a file. By default, it displays the first 10 lines.

View first 10 lines:

head filename.txt

View first 100 lines:

head -100 filename.txt

Practical example – check WordPress config:

head -20 wp-config.php

Using the tail command

The tail command shows you the last lines of a file, perfect for checking recent log entries.

View last 10 lines:

tail filename.txt

View last 100 lines:

tail -100 filename.txt

Practical example – check recent errors:

tail -50 error_log

Monitor files in real-time

The most useful feature of tail is watching files as they update in real-time, essential for monitoring logs.

Follow a file (watch for new lines):

tail -f /var/log/access.log

This keeps running and shows new lines as they’re added. Press Ctrl+C to stop.

Follow multiple files:

tail -f error.log access.log

View specific line ranges

Combine head and tail to extract specific sections of a file.

View lines 50-60:

head -60 filename.txt | tail -10

This gets the first 60 lines, then shows the last 10 of those (lines 51-60).

Get exactly line 25:

head -25 filename.txt | tail -1

Common use cases

Here are the most common scenarios for web hosting and server management:

1. Check recent errors:

tail -100 ~/public_html/error_log

2. Monitor website traffic in real-time:

tail -f ~/logs/access.log

3. Check CSV file headers:

head -1 data.csv

4. Verify backup completion:

tail -20 backup.log

5. Search recent log entries:

tail -500 access.log | grep "404"

Quick tips

  • Use tail -f for live log monitoring instead of repeatedly opening files
  • Combine with grep to filter results: tail -100 error.log | grep "PHP"
  • Save output to files: head -1000 large.txt > sample.txt
  • Both commands work with any text file regardless of size

For more file management commands, check our guides on listing files with the ls command and finding files using SSH.

Get hosting with SSH access

Need reliable shared hosting with SSH access? Our hosting plans include SSH access, allowing you to manage files and monitor logs efficiently. Additionally, enjoy 80% OFF for new customers.

Discover more Linux tutorials in our knowledgebase.