How to Use Head and Tail Commands in Bash
In bash, use
head to display the first lines of a file or output, and tail to show the last lines. Both commands accept options like -n to specify how many lines to show, for example, head -n 5 filename shows the first 5 lines.Syntax
The basic syntax for head and tail commands is:
head [options] [file]- shows the first part of the file.tail [options] [file]- shows the last part of the file.- The
-noption lets you specify the number of lines to display.
bash
head -n 10 filename tail -n 10 filename
Example
This example shows how to use head and tail to display the first 3 and last 3 lines of a sample file named example.txt.
bash
echo -e "line1\nline2\nline3\nline4\nline5" > example.txt head -n 3 example.txt tail -n 3 example.txt
Output
line1
line2
line3
line3
line4
line5
Common Pitfalls
Common mistakes include:
- Forgetting to specify
-nwhen you want a specific number of lines (default is 10). - Using
headortailwithout a file or input, which waits for input from the keyboard. - Confusing
headandtailwhen trying to see the start or end of data.
bash
head example.txt # This shows first 10 lines by default head -n 5 example.txt # Correct way to get first 5 lines # Wrong: tail -n 5 example.txt | head -n 3 # This shows last 5 lines first, then first 3 of those, which may confuse beginners
Quick Reference
| Command | Description | Example |
|---|---|---|
| head -n 5 filename | Show first 5 lines of file | head -n 5 example.txt |
| tail -n 5 filename | Show last 5 lines of file | tail -n 5 example.txt |
| head filename | Show first 10 lines (default) | head example.txt |
| tail filename | Show last 10 lines (default) | tail example.txt |
Key Takeaways
Use
head -n and tail -n to control how many lines you see.By default, both commands show 10 lines if
-n is not specified.Always specify a file or pipe input to avoid waiting for keyboard input.
Remember
head shows the start, tail shows the end of data.