0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use Head Command in Linux: Syntax and Examples

The head command in Linux shows the first part of a file or input, usually the first 10 lines by default. You can specify the number of lines with -n or bytes with -c options to control the output.
📐

Syntax

The basic syntax of the head command is:

  • head [options] [file]

Where:

  • options control how many lines or bytes to show.
  • file is the name of the file to read. If omitted, head reads from standard input.

Common options include:

  • -n N: Show the first N lines.
  • -c N: Show the first N bytes.
bash
head -n 5 filename.txt
💻

Example

This example shows how to display the first 3 lines of a file named example.txt. It helps you quickly see the start of a file without opening the whole content.

bash
head -n 3 example.txt
Output
Line 1: Introduction to Linux Line 2: Using basic commands Line 3: Understanding files
⚠️

Common Pitfalls

Some common mistakes when using head include:

  • Forgetting to specify the number of lines with -n and expecting a different default than 10 lines.
  • Using head on a binary file without -c, which can produce unreadable output.
  • Not providing a file or input, which causes head to wait for input from the keyboard.

Correct usage example:

head -n 5 file.txt

Incorrect usage example (waiting for input):

head
📊

Quick Reference

OptionDescription
-n NShow first N lines of the file
-c NShow first N bytes of the file
-qSuppress headers when multiple files are shown
-vAlways show headers with file names

Key Takeaways

Use head to quickly view the first lines of a file or input.
Specify the number of lines with -n or bytes with -c options.
If no file is given, head reads from standard input until interrupted.
Default output is the first 10 lines if no options are specified.
Avoid using head on binary files without -c to prevent unreadable output.