How to use head and tail to View File Excerpts in Linux

Learn how to use head and tail commands in Linux to quickly view excerpts from files. This tutorial provides step-by-step instructions and examples for efficient file previewing.

Head and tail

  • head: Display the first 10 lines of a file
    • Use -n to change number of lines displayed
  • tail: Display the last 10 lines of a file
    • Use -n to change number of lines displayed
    • Use -f to “follow” subsequent additions to the file
      • Very useful for monitoring log files!

The head command is used to display just the first few lines of a file. The default is 10 lines.

head /etc/passwd
Viewing File Excerpts Head and Tail

-n specifies the number of lines to display:
head -n 3 /etc/passwd

Viewing File Excerpts Head and Tail

tail is used to display the last few lines of a file. The default is 10. tail is often used by the system administrator to read the most recent entries in log files.
tail -n 3 /var/log/cron

Viewing File Excerpts Head and Tail

Using -f causes tail to continue to display the file in “real time”, showing additions to the end of the file as they occur. This is very useful for watching growing files, such as the output of the make command. System administrators use this feature to keep an eye on the system log using the following command:
tail -f /var/log/messages

tail -f will continue to show updates to the file until Ctrl-c is pressed.

Leave a Comment