Menu
CoddyTech

Head And Tail

Part of the Fundamentals section of Coddy's Terminal journey. Lesson 30 of 82.

When working with large files, you often don't need to read the entire file. You just need to see the beginning or the end. The head and tail commands let you do exactly that.

The head command shows the first lines of a file. By default it shows the first 10 lines:

head log.txt

To specify how many lines to show, use the -n flag:

head -n 3 log.txt   # show first 3 lines
head -n 1 log.txt   # show only the first line

The tail command shows the last lines of a file. By default it shows the last 10 lines:

tail log.txt

To specify how many lines:

tail -n 3 log.txt   # show last 3 lines
tail -n 1 log.txt   # show only the last line

When to use each:

  • Use head to preview the structure or header of a file
  • Use tail to check the most recent entries in a log file

A useful trick: combining both:

You can use both commands together to see the start and end of a file at the same time:

head -n 2 log.txt
tail -n 2 log.txt
challenge icon

Challenge

Beginner
Use head and tail to inspect log.txt. Run both commands, head first and then tail. You can type them on two lines, or on one line separated by a semicolon (;):

1. Print the first 3 lines of the file using head -n 3 log.txt
2. Print the last 1 line of the file using tail -n 1 log.txt

One-line format: command1; command2
Hint: The semicolon ; runs several commands one after the other on a single line.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Terminal playground