🔝 Command: head (View the Beginning of a File)
The head command is a simple utility that displays the first part of a file. By default, it shows the first 10 lines.
1. The "Why"
When you are working with large data files, logs, or long code documents, you often don't need to see the whole thing. You might just want to:
- Check the header of a CSV file to see the column names.
- Verify the
packageorimportstatements at the top of a file. - Quickly identify the contents of a file without opening a pager like
less.
2. Basic Syntax
head [OPTIONS] [FILE]
- Example:
head config.txtwill output the first 10 lines of the file.
3. Most Useful Flags
| Flag | Name | What it does |
|---|---|---|
-n [number] |
Lines | Specify exactly how many lines you want to see. |
-c [number] |
Bytes | Shows the first N bytes (characters) instead of lines. |
-q |
Quiet | Suppresses the header showing the filename (useful when checking multiple files). |
-v |
Verbose | Always shows the header with the filename. |
4. Practical Examples
A. Seeing More (or Less) than 10 Lines
If you want to see the first 20 lines of your e-book draft:
head -n 20 chapter1.tex
Tip: You can also just type head -20 chapter1.tex for the same result.
B. Checking the Preamble of Multiple Files
If you want to make sure all your LaTeX chapters have the correct initial setup:
head -n 5 *.tex
This will show the first 5 lines of every .tex file, with a small header above each section telling you which file is which.
C. Using Pipes to Filter Output
A very common use for head is to limit the output of another command. For example, to see only the first 5 commands available on your system:
compgen -c | head -n 5
D. Viewing the "First Bytes"
If you are dealing with a binary file or a very long string and only want the first 50 characters:
head -c 50 data.bin
5. Pro-Tips
- Combining with Tail: You can use
headandtailtogether to grab a specific range of lines. For example, to see only lines 10 through 15:head -n 15 file.txt | tail -n 6 - Default Behavior: If you find yourself always needing 20 lines instead of 10, you can't easily change the default, but you can create an alias in your
.bashrc:alias head20='head -n 20'. - Arch Linux Context: You'll use this often when inspecting system files like
/etc/fstabor checking the beginning of a longdmesgoutput to see boot-up information.
6. Summary Reference
| Goal | Command |
|---|---|
| See first 10 lines | head filename |
| See first 5 lines | head -n 5 filename |
| See first 100 bytes | head -c 100 filename |
| See start of multiple files | head file1 file2 |