head and tail Commands in Linux — View File Beginnings & Endings
The head and tail commands display the beginning and end of files in Linux — essential for previewing data, monitoring logs in real-time, and debugging live systems without loading entire files into memory.
What You’ll Learn
You’ll view first and last N lines/bytes, follow log files as they grow, handle log rotation with tail -F, monitor multiple files, and build real-time log monitoring pipelines with grep.
Why head and tail Matter
Log files grow continuously — you can’t open a 2GB syslog in a text editor. tail lets you watch new entries as they’re written. head gives you a quick peek at file structure without scrolling. DodaZIP uses tail -F to monitor compression job logs, and Durga Antivirus Pro streams real-time scan events through tail | grep pipelines for live alerting.
Learning Path
flowchart LR
A[Essential Commands] --> B[File Viewing Tools]
B --> C[head & tail<br/>You are here]
C --> D[Log Monitoring]
C --> E[grep & awk]
style C fill:#f90,color:#fff
Syntax Overview
head [options] [file...]
tail [options] [file...]head Options Table
| Option | Description |
|---|---|
-n N | Show first N lines (default: 10) |
-c N | Show first N bytes |
-q | Quiet — suppress filename headers |
-v | Verbose — always show filename headers |
tail Options Table
| Option | Description |
|---|---|
-n N | Show last N lines (default: 10) |
-f | Follow — watch file for new content in real-time |
-F | Follow with rotation — handles log rotation |
-c N | Show last N bytes |
-q | Quiet — suppress headers |
--pid=PID | Stop following when PID exits |
-s SEC | Sleep interval between checks (default: 1.0) |
Examples
Example 1: head -n — First N Lines
$ head -n 5 /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/syncShows the first 5 lines of the password file. Without -n, head defaults to 10 lines.
Example 2: tail -n — Last N Lines
$ tail -n 3 /etc/passwd
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-resolve:x:100:102:systemd Resolver,,,:/run/systemd:/usr/sbin/nologin
user:x:1000:1000:user,,,:/home/user:/bin/bashShows the last 3 lines.
Example 3: tail -f — Follow Log in Real-Time
$ tail -f /var/log/syslog
Jun 20 10:00:01 server systemd[1]: Starting Daily apt upgrade...
Jun 20 10:00:02 server systemd[1]: Started Daily apt upgrade.
Jun 20 10:00:05 server sshd[1234]: Accepted publickey for user from 192.168.1.5
Jun 20 10:00:12 server kernel: [12345.678] eth0: link upPress Ctrl+C to stop following. New lines appear as they’re written.
Example 4: tail -F — Follow with Log Rotation
$ tail -F /var/log/nginx/access.log
192.168.1.1 - - [20/Jun/2026:10:00:00 +0000] "GET / HTTP/1.1" 200 1234
192.168.1.2 - - [20/Jun/2026:10:00:01 +0000] "GET /about HTTP/1.1" 200 567-F (capital F) reopens the file if it’s rotated — crucial for production log monitoring.
Example 5: head/tail by Bytes (-c)
$ head -c 20 /etc/hostname
my-server
$ tail -c 50 /var/log/syslog
...up 2026 Jun 20 10:00:00 my-server kernel: eth0: link upUseful for reading fixed-size records or checking file signatures.
Example 6: Multiple Files (-q)
$ head -n 2 -q file1.txt file2.txt
First line of file1
Second line of file1
First line of file2
Second line of file2With -q, no filename headers are shown. Without it, head/tail prints ==> filename <== before each file.
Example 7: tail with grep for Log Monitoring
$ tail -F /var/log/syslog | grep "ERROR"
Jun 20 10:05:00 server app[5678]: ERROR: Database connection failed
Jun 20 10:05:01 server app[5678]: ERROR: Retry attempt 1/3This pipeline streams log entries and filters for ERROR lines in real-time — the most common sysadmin monitoring pattern.
Example 8: head with Pipe
$ sort -rn scores.txt | head -3
98 Alice
95 Bob
91 CarolSorts data and shows only the top 3 results — a pattern used for leaderboards, top processes, and largest files.
Example 9: Show Lines Around a Specific Line
# Find the line number, then show context
$ grep -n "ERROR" /var/log/app.log
42:ERROR: Connection timeout
$ tail -n +40 /var/log/app.log | head -n 10
40: INFO: Starting service
41: WARN: Low memory
42: ERROR: Connection timeout
43: INFO: Retrying...
44: INFO: ReconnectedUses tail -n +N to start from line N, then head to limit output.
Example 10: Display Both Start and End of File
$ (head -n 3; tail -n 3) < /var/log/syslog
Jun 20 00:00:01 server systemd[1]: Starting system update
Jun 20 00:00:02 server systemd[1]: Started system update
Jun 20 00:00:05 server kernel: [0.000000] Linux version...
Jun 20 09:59:55 server CRON[9999]: (root) END (daily cron)
Jun 20 10:00:00 server systemd[1]: Starting daily cleanup...
Jun 20 10:00:01 server systemd[1]: Started daily cleanup...Shows first and last 3 lines — a quick overview of log file activity across an entire day.
Common Use Cases
| Use Case | Command |
|---|---|
| Peek at CSV headers | head -1 data.csv |
| Watch error log live | tail -f /var/log/nginx/error.log |
| Monitor with rotation | tail -F /var/log/syslog |
| Top 5 largest files | du -sh * | sort -h | tail -5 |
| Skip header row | tail -n +2 data.csv | head -5 |
| Live alert filter | tail -F /var/log/auth.log | grep "Failed password" |
Common Errors
- tail -f on rotated log: If the file is rotated,
-fcontinues following the old (now deleted) file. Always use-F. - head -n 0: Shows nothing. Use
head -n 1for the first line. - Very large files: head and tail are efficient for any file size — they don’t read the whole file. But
tail -n +1000000still reads from the start until it finds the right position. - tail -f never exits: Inside scripts, use
--pid=PIDortimeoutto stop tail after a condition. - Binary output: tail/head work on binary files but output may look garbled on terminal. Pipe to
hexdumporodfor readable output.
Practice Exercises
- head basics: Display the first 15 lines of any file.
- tail basics: Display the last 20 lines of a log.
- Follow + filter: Run
tail -f /var/log/syslogand filter for a specific keyword. - Byte count: Extract the first 100 bytes of a binary file and save to a new file.
- Skip header: Use tail to skip the first line of a CSV and pass to head.
Challenge
Write a monitoring script that watches /var/log/auth.log for failed SSH attempts. When 5 or more failures from the same IP occur within 60 seconds, send an alert. Durga Antivirus Pro uses this pattern to detect brute-force attacks in real time.
#!/bin/bash
LOG="/var/log/auth.log"
tail -F "$LOG" | while read line; do
if echo "$line" | grep -q "Failed password"; then
IP=$(echo "$line" | grep -oP 'from \K[0-9.]+')
echo "$(date): Failed attempt from $IP"
fi
doneReal-World Task
A production web server is experiencing intermittent 502 errors. Use tail to monitor the error log live, filter for “502” entries, and correlate timestamps with access log patterns to identify the root cause.
Solution: Open two terminals — one running tail -F /var/log/nginx/error.log \| grep "502" and another running tail -F /var/log/nginx/access.log. Compare timestamps to find the pattern.
What is head?
The head command outputs the first N lines (or bytes) of a file, defaulting to 10 lines — ideal for previewing file contents without opening the entire file.
What is tail?
The tail command outputs the last N lines of a file, with -f mode for real-time monitoring of growing files — the primary tool for log observation.
Related Tutorials
- Essential Linux Commands — file viewing tools overview
- grep Pattern Matching — combine with tail for log filtering
- Bash Scripting Guide — automate log monitoring
- Linux Administration Basics — foundational admin skills
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro