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:
optionscontrol how many lines or bytes to show.fileis the name of the file to read. If omitted,headreads 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.txtExample
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.txtOutput
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
-nand expecting a different default than 10 lines. - Using
headon a binary file without-c, which can produce unreadable output. - Not providing a file or input, which causes
headto wait for input from the keyboard.
Correct usage example:
head -n 5 file.txt
Incorrect usage example (waiting for input):
head
Quick Reference
| Option | Description |
|---|---|
| -n N | Show first N lines of the file |
| -c N | Show first N bytes of the file |
| -q | Suppress headers when multiple files are shown |
| -v | Always 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.