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 read•Last updated: 2024
Dai Aoki
CEO at init, Inc. / CTO at US & JP startups / Creator of WebTerm
Quick Reference
Basic
head file.txtFirst 10 lineshead -n 5 fileFirst 5 lineshead -n -5 fileAll except last 5Options
-n NUMShow NUM lines-c NUMShow NUM bytes-qQuiet (no headers)Common
head -1 fileFirst line onlyhead f1.txt f2.txtMultiple filescmd | head -20Pipe usageDownloadable Image Preview
Failed to generate preview
Basic Usage
By default, head displays the first 10 lines of a file.
bash
head filename.txtCommon Options
head Options
| -n N | Display first N lines |
| -c N | Display first N bytes |
| -q | Quiet mode (no headers for multiple files) |
| -v | Always 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.txtDisplay 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.txtMultiple 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.txtPractical Examples
Preview log file
bash
head -n 20 /var/log/syslogCheck CSV headers
bash
head -n 1 data.csvCombine 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 5Extract file header/magic bytes
bash
# Check file signature (first 4 bytes)
head -c 4 file.pdf | xxdTip
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.txtSummary
head is simple but essential for previewing files. Key takeaways:
- Use
head -n Nfor first N lines - Use
head -c Nfor first N bytes - Use
head -n -Nto exclude last N lines - Great for checking file headers and limiting command output