Head and Tail
The head and tail commands show the beginning or end of files. They're essential for previewing files and monitoring logs.
head - View Beginning
head filename
By default, shows first 10 lines.
tail - View End
tail filename
By default, shows last 10 lines.
Specifying Number of Lines
head Options
head -n 5 file.txt # First 5 lines
head -5 file.txt # Same thing (shorthand)
head -n -5 file.txt # All BUT last 5 lines
tail Options
tail -n 5 file.txt # Last 5 lines
tail -5 file.txt # Same thing (shorthand)
tail -n +5 file.txt # Starting from line 5
Follow Mode (tail -f)
Watch a file for changes in real-time:
tail -f /var/log/syslog
This is invaluable for monitoring logs. Press Ctrl+C to stop.
Exercise: View First Lines
View the first 3 lines of a log file:
Common Options
| Command | Description |
|---|---|
head -n 20 | First 20 lines |
tail -n 20 | Last 20 lines |
tail -f | Follow file (live updates) |
tail -F | Follow, even if rotated |
head -c 100 | First 100 bytes |
tail -c 100 | Last 100 bytes |
Combining with Pipes
Get Lines from Middle
head -n 20 file.txt | tail -n 10 # Lines 11-20
Preview Multiple Files
head -n 5 *.txt
Monitor Multiple Logs
tail -f /var/log/*.log
Real-World Examples
Check Recent Log Entries
tail -n 50 /var/log/syslog
Monitor Log in Real-Time
tail -f /var/log/auth.log
Quick File Preview
head README.md
head -n 1 /etc/passwd # Just first line
Extract Specific Range
# Lines 100-110
head -n 110 file.txt | tail -n 10
Exercise: View Last Lines
View the last 2 lines of a config file:
Key Takeaways
headshows beginning,tailshows end- Default is 10 lines, use
-nto change tail -ffollows file changes in real-time- Essential for log monitoring
- Combine with pipes for precise line selection
التالي · الدرس 16 من 40
Counting with wc
قراءة 2 دقيقة
أنهيت 15 من 40 درسًا

اسأل Byte عن هذا الدرس
محادثة خاصة حول هذا الدرس. قرأ Byte الدرس كاملًا، ويجيب خلال ثوانٍ، ويُظهر القسم الذي تأتي منه كل إجابة. يمكنك السؤال بأي لغة.
الأسئلة والأجوبة
أسئلة عامة حول هذا الدرس. يجيب AI Tutor فورًا بلغتك، ويراجع فريق FreeAcademy الإجابات، ويمكن لكل المتعلمين قراءتها.

