head Command: Tutorial & Examples
Display the First Few Lines of a File Quickly
The head command is a powerful command-line utility that outputs the beginning portion of text files or data streams. By default, it displays the first 10 lines, providing a fast and efficient way to peek into large files or logs without opening them entirely. This capability is essential for system administrators, developers, and anyone working on Linux servers who need to inspect file contents quickly and automate processing in shell scripts or pipelines.
head was created to address the need for efficient file previews and partial content extraction, enabling users to avoid loading entire files into memory. It works seamlessly with other command-line tools, making it a fundamental component of Linux text processing.
How head Works
When invoked, head opens the specified file(s) or reads from standard input if no file is given. It reads sequentially from the start, outputting the requested amount of data—usually lines or bytes—to standard output. Once the specified number of lines or bytes is reached, head stops reading further, optimizing performance especially for large files.
Internally, head uses buffered I/O to improve speed and handles multiple files one after another. When multiple files are provided, it outputs a header containing the file name before printing its content, unless suppressed by options. When reading from pipes or special devices, head reads until the requested data is output; however, care must be taken with infinite data streams as head might block waiting for input.
What head Does
head outputs the first part of one or more files. By default, this is the first 10 lines, but users can customize this to any number of lines or bytes. Typical use cases include:
- Previewing file headers or metadata in configuration and data files.
- Examining the start of log files for recent entries or error messages.
- Limiting output in scripts and pipelines to reduce processing overhead.
- Quickly inspecting command output or filtering data streams.
When multiple files are specified, head prints each file’s output preceded by a filename header, helping distinguish content sources.
Common Command Line Parameters
head provides several options to tailor its output:
-n NUM or --lines=NUM
Output the first NUM lines of each file (default is 10 lines). NUM may be positive or, in GNU implementations, negative to exclude lines from the end.Example:
head -n 5 /var/log/syslog
-c NUM or --bytes=NUM
Output the first NUM bytes of each file instead of lines.Example:
head -c 100 /etc/hostname
-q or --quiet or --silent
Suppress printing headers when processing multiple files.-v or --verbose
Always print headers before each file’s output, even if only one file is given.
Additional options may exist depending on the Linux distribution and coreutils version.
Basic Usage Examples
Display the first 10 lines of a file (default):
head /etc/passwd
Display the first 20 lines of a log file:
head -n 20 /var/log/auth.log
Display the first 50 bytes of a file:
head -c 50 /etc/hostname
View the first 5 lines of multiple files with headers:
head -n 5 /etc/passwd /etc/group
Sample output:
==> /etc/passwd <==
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
==> /etc/group <==
root:x:0:
daemon:x:1:
bin:x:2:
sys:x:3:
adm:x:4:syslog
Advanced Usage and Tips
Using negative numbers with
-n
(GNU coreutils only) outputs all but the last N lines:head -n -5 file.txt
Combine head with
grep
to preview the first matching lines:grep "error" /var/log/syslog | head -n 10
Use head with paginators like
less
:head -n 100 file.log | less
Redirect head output for inspection or further processing:
head -n 50 bigfile.txt > preview.txt
In scripts, use head to limit data processed, improving performance and reducing memory usage.
Common Errors and Troubleshooting
head: cannot open 'filename' for reading: No such file or directory
The specified file does not exist or the path is incorrect. Verify the filename and path.head: error reading 'filename': Permission denied
Insufficient permissions to read the file. Usesudo
if appropriate, or check file ownership and permissions.Unexpected output with binary files
head is designed for text files; binary files may yield unreadable or garbled output.Negative numbers with
-n
may not be supported in all versions. Confirm your version:head --version
Using head on infinite streams or devices without limiting lines or bytes may cause the command to hang.
Scripting and Automation
head is widely used in shell scripts and automation tasks to extract file headers or limit output size. Example: a cron job to save the first 20 lines of an access log every 5 minutes:
*/5 * * * * /usr/bin/head -n 20 /var/log/nginx/access.log > /tmp/access_head.log
Sample script snippet checking file existence and displaying its first 10 lines:
if [ -f /var/log/syslog ]; then
head -n 10 /var/log/syslog
else
echo "Log file not found."
fi
head can help optimize scripts by reducing data processed, improving speed and resource usage.
Performance Considerations
head reads only the requested data portion, making it efficient for large files. Some points to consider:
- Using byte mode (
-c
) can be faster when exact byte counts are needed. - Reading from pipes or devices producing infinite data without limits may cause head to block.
- Buffered I/O enhances speed but combining head with other heavy commands might affect performance.
- head reads files sequentially from the beginning, so avoid using it repeatedly on very large files if possible.
Security Considerations
- Using head on files containing sensitive information requires appropriate permissions to prevent unauthorized data exposure.
- Ensure scripts using head do not inadvertently leak data via logs or temporary files.
- Be cautious when running head with elevated privileges to avoid privilege escalation risks.
Alternatives and Related Commands
tail
: Show the last portion of files.sed
: Stream editor, useful for extracting lines.awk
: Powerful text processing language.more
andless
: Paginated file viewers.cut
: Extract specific columns or sections from lines.
Cheatsheet
Display first 10 lines (default):
head file.txt
Display first 5 lines:
head -n 5 file.txt
Display first 100 bytes:
head -c 100 file.txt
Display first 3 lines of multiple files without headers:
head -q -n 3 file1 file2
Display first 3 lines with header even for a single file:
head -v -n 3 file1
See Also
Further Reading
- Bash Cookbook by Carl Albing, J.P. Vossen (partner link)
- Wicked Cool Shell Scripts by Dave Taylor, Brandon Perry (partner link)
- Black Hat Bash by Nick Aleks, Dolev Farhi (partner link)
- Bash Pocket Reference by Arnold Robbins (partner link)
- The Linux Command Line by William Shotts (partner link)
- Learning the Bash Shell by Cameron Newham (partner link)
- Mastering Linux Shell Scripting by Mokhtar Ebrahim, Andrew Mallett (partner link)
- Linux Command Line and Shell Scripting Bible by Richard Blum, Christine Bresnahan (partner link)
- Shell Scripting by Jason Cannon (partner link)
As an Amazon Associate, I earn from qualifying purchases.