head Command Cheat Sheet
head prints the first part (default 10 lines) of each given file. It is the counterpart to tail.
Synopsis
head [OPTION]... [FILE]...
Basic Usage
Show First 10 Lines
head filename.txt
Show First N Lines (-n)
head -n 20 filename.txt
head -20 filename.txt
Advanced Options
Show First N Bytes (-c)
Useful for binary files or specific data extraction.
head -c 100 image.png
Suffixes allowed:
- b: 512
- kB: 1000
- K: 1024
- MB: 10001000
- M: 10241024
head -c 1M large.iso > header.img
Show All EXCEPT Last N Lines
Negative numbers with -n print everything except the last N lines.
head -n -5 filename.txt
Multiple Files
When multiple files are provided, head prints a header ==> filename <== before each one.
head file1.txt file2.txt
==> file1.txt <==
Line 1...
Line 2...
==> file2.txt <==
Line 1...
Suppress Headers (-q): Quiet mode. Never print headers.
head -q file1.txt file2.txt
Always Print Headers (-v): Verbose mode. Print headers even for a single file.
head -v file1.txt
Pipeline Examples
View Top Processes
Combine with ps and sort.
ps aux --sort=-%mem | head -n 6
Verify Archive Integrity
Check the first few bytes of a file to verify its type signature.
head -c 4 file.pdf
# Output: %PDF
Random Password Generation
Limit the output of /dev/urandom.
tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 16; echo
Exit Status
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | Error reading file |
Notes
headreads from Standard Input if no file is specified.- It stops reading as soon as the limit is reached, making it efficient for large files (unlike
cat).