How to use tail and head for log analysis

· Category: Linux

Short answer

head shows the start of a file; tail shows the end and can follow files in real time.

Steps

  1. View first 10 lines:
head file.txt
  1. View last 20 lines:
tail -n 20 file.txt
  1. Follow a log in real time:
tail -f /var/log/syslog
  1. Combine:
cat file.txt | head -50 | tail -10

Tips

  • tail -F follows across log rotations.
  • Use grep piped into tail to filter then view recent matches.
  • head and tail work on piped input, not just files.

Common issues

  • tail -f stops when the file is truncated; use -F for robust following.
  • Binary files may produce garbled output.