Terminal GuideTerminal Guide

head Command Guide

The head command displays the first part of files. Learn how to quickly preview file contents without loading the entire file.

4 min readLast updated: 2024
Dai Aoki

Dai Aoki

CEO at init, Inc. / CTO at US & JP startups / Creator of WebTerm

Quick Reference

Basic

head file.txtFirst 10 lines
head -n 5 fileFirst 5 lines
head -n -5 fileAll except last 5

Options

-n NUMShow NUM lines
-c NUMShow NUM bytes
-qQuiet (no headers)

Common

head -1 fileFirst line only
head f1.txt f2.txtMultiple files
cmd | head -20Pipe usage

Downloadable Image Preview

Failed to generate preview

Basic Usage

By default, head displays the first 10 lines of a file.

bash
head filename.txt

Common Options

head Options

-n NDisplay first N lines
-c NDisplay first N bytes
-qQuiet mode (no headers for multiple files)
-vAlways show filename headers

Specifying Number of Lines

bash
# Display first 5 lines
head -n 5 file.txt

# Short form
head -5 file.txt

# Display all but last 5 lines
head -n -5 file.txt

Display Bytes Instead of Lines

bash
# First 100 bytes
head -c 100 file.txt

# First 1KB
head -c 1K file.txt

# First 1MB
head -c 1M file.txt

Multiple Files

bash
# Display first 5 lines of each file
head -n 5 file1.txt file2.txt file3.txt

# Suppress headers
head -q -n 5 file1.txt file2.txt

Practical Examples

Preview log file

bash
head -n 20 /var/log/syslog

Check CSV headers

bash
head -n 1 data.csv

Combine with other commands

bash
# First 10 largest files
ls -lhS | head -n 11

# Top 5 memory-consuming processes
ps aux --sort=-%mem | head -n 6

# First 5 matches from grep
grep "error" log.txt | head -n 5

Extract file header/magic bytes

bash
# Check file signature (first 4 bytes)
head -c 4 file.pdf | xxd
Tip
Use head with pipes to limit output from commands that produce many lines.

head vs tail

While head shows the beginning, tail shows the end of files.

bash
# Show first and last 5 lines
head -n 5 file.txt && tail -n 5 file.txt

# Or using sed
sed -n '1,5p;$p' file.txt

Summary

head is simple but essential for previewing files. Key takeaways:

  • Use head -n N for first N lines
  • Use head -c N for first N bytes
  • Use head -n -N to exclude last N lines
  • Great for checking file headers and limiting command output

Related Articles