cat, head & tail

Read a file

Lesson 4 of 20 · 8 min · Module 1: Find your way around

Most of what you read on a server is text: logs, settings, and reports. You do not need an editor to look inside.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Print a whole file
  • Show the beginning or end of a file
  • Choose the right tool for a large file

The idea

cat file prints a whole file. head -n 3 file shows the first three lines and tail -n 2 file the last two. Without -n, both show ten lines. Logs grow at the bottom, so tail shows the newest events.

cat notes.txt
head -n 2 logs/app.log
tail -n 1 logs/app.log

01cat prints everything

cat is short for concatenate: give it several files and it prints them one after another. It is perfect for short files.

cat notes.txt
Output
Buy coffee
Learn Linux
Call Sam
Back up the website

02head and tail take a slice

A log can have millions of lines. head -n 5 shows the start and tail -n 5 the end, without flooding your screen. Many people also write the shorter form tail -5.

03Newest events are at the bottom

Programs append new log lines at the end of the file, so tail shows what just happened. On a real server, tail -f keeps the file open and prints new lines as they arrive.

Your turn

Show the first 3 lines of logs/app.log, then the last 2 lines of the same file.

What the checks look for

  • Shows exactly the first 3 log lines
  • Shows exactly the last 2 log lines
Try it in the editor →

Take this with you

Use cat for small files, head for the beginning, and tail for the latest lines.

Go a little further

Use cat -n notes.txt to print the file with line numbers.

Learn Linux Command Line for free

20 short lessons with real code and instant checks.

See the whole course →