Menu
Coddy logo textTech

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 <strong>head</strong> 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 <strong>tail</strong> 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:

  1. Print the first 3 lines of the file using head
  2. Print the last 1 line of the file using tail

Hint: Use the -n flag to control how many lines are shown. Run both commands one after the other.

Cheat sheet

The head command shows the first lines of a file (default: 10 lines):

head log.txt

The tail command shows the last lines of a file (default: 10 lines):

tail log.txt

Use the -n flag to specify the number of lines:

head -n 3 log.txt   # show first 3 lines
tail -n 1 log.txt   # show last 1 line

You can combine both commands to see the start and end of a file:

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

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