CommandsLinux

Head Command in Linux with Examples

Head Command in Linux

The head command stands as one of the most practical utilities in the Linux toolkit, providing a straightforward yet powerful way to examine the beginning portions of files. Whether you’re a system administrator monitoring logs, a developer debugging code, or a Linux enthusiast learning the ropes, mastering the head command can significantly enhance your efficiency in handling text files. This comprehensive guide explores everything from basic functionality to advanced techniques, giving you the expertise to leverage this command to its fullest potential.

Understanding the Head Command Basics

The head command in Linux is designed with a singular purpose: to display the beginning section of a file or standard input. By default, head outputs the first 10 lines of the specified file, making it an invaluable tool for quickly previewing file contents without loading entire files into memory. This functionality proves especially useful when working with large logs or data files where opening the complete file might be resource-intensive.

At its most fundamental level, head operates as a filter that extracts and displays the initial portion of text files. Unlike text editors that load entire files, head efficiently reads only what it needs, making it remarkably performant even with extremely large files. This efficiency makes it an essential utility for system administrators who frequently need to check log files or configuration file headers.

Basic Syntax Structure

The standard syntax for the head command follows this pattern:

head [OPTION]... [FILE]...

Where [OPTION] represents various modifiers that control how head processes files, and [FILE] specifies one or more target files. When no options are specified, head simply displays the first 10 lines of each named file. If no file is specified, head reads from standard input, allowing it to work seamlessly in command pipelines.

Default Behavior

By default, when you run head filename.txt, the command will output the first 10 lines of the specified file. This behavior provides a quick glimpse into a file’s content without overwhelming the terminal with excessive output. The default value of 10 lines strikes a practical balance between brevity and informativeness for most use cases.

Exit Status Codes

Like most Linux commands, head returns status codes that indicate the success or failure of its operation. A zero exit status indicates successful execution, while non-zero values signal various error conditions. Understanding these exit codes can be crucial when incorporating head into scripts where error handling is important.

Essential Command Options

The head command’s versatility comes from its various options that allow you to customize how it processes and displays file content. Mastering these options transforms head from a simple utility into a powerful tool for daily system administration and file management tasks.

Controlling Line Output (-n, –lines)

The most commonly used option with head is -n (or its long form --lines), which allows you to specify exactly how many lines you want to display. This provides precise control over the output volume:

head -n 15 /var/log/syslog

This command displays the first 15 lines of the system log file instead of the default 10 lines. You can also use a negative number to display all but the last N lines of a file:

head -n -5 filename.txt

This would display all lines except the last 5 lines of the file, which can be particularly useful in certain scripting scenarios.

Controlling Byte Output (-c, –bytes)

When you need even more precise control, the -c (or --bytes) option allows you to specify output by exact byte count rather than by lines:

head -c 100 binaryfile.bin

This command outputs exactly the first 100 bytes of the specified file. This option proves especially valuable when working with binary files or when you need to extract a specific header portion of a file.

The -c option also supports multiplier suffixes for convenience:

  • b (512-byte blocks)
  • k or KB (kilobytes)
  • m or MB (megabytes)

For example:

head -c 1k filename.txt

This displays the first kilobyte of data from the file.

Displaying File Names (-v, –verbose)

When working with multiple files, the -v (or --verbose) option forces head to always display file names before showing the content of each file, even if only one file is processed:

head -v filename.txt

This option helps maintain clarity when scripting or when processing sets of files with similar content.

Suppressing File Names (-q, –quiet)

Conversely, the -q (or --quiet) option suppresses the printing of headers that identify file names. This can be useful when you want to process the output programmatically without header interference:

head -q file1.txt file2.txt

This command displays the content from both files without the separating headers, creating a clean, uninterrupted output stream.

Working with Multiple Files

One of the head command’s key strengths is its ability to process multiple files simultaneously, making comparative analysis and batch processing remarkably straightforward.

Basic Multi-file Syntax

To view the beginning sections of multiple files at once, simply list them as arguments to the head command:

head file1.txt file2.txt file3.txt

This command will display the first 10 lines of each file, one after another.

Output Format with Multiple Files

By default, when head processes multiple files, it prepends each file’s content with a header line containing the file name:

==> file1.txt <== (content of file1) ==> file2.txt <==
(content of file2)

This format clearly delineates which content belongs to which file, making the output easy to interpret even when dealing with numerous files.

Comparing Initial Contents

This multi-file capability makes head particularly useful for quickly comparing the beginnings of similar files. For example, system administrators can simultaneously check the headers of multiple log files to identify patterns or anomalies:

head /var/log/syslog /var/log/auth.log /var/log/messages

This allows for quick detection of issues across multiple system logs without opening each file individually.

Output Control Options

When working with multiple files, the -q and -v options become especially valuable:

  • Use -q to suppress file headers, creating a continuous stream of text from all files
  • Use -v to ensure file headers are always displayed, even if only one file is specified

These options give you precise control over the format of multi-file output, adapting to different workflow requirements.

Head Command in Pipelines

The head command truly shines when integrated into command pipelines, where it works in concert with other Linux utilities to create powerful data processing workflows.

Receiving Piped Input

Head can process data received from other commands through pipelines, filtering and limiting their output:

cat large_file.txt | head

This command displays only the first 10 lines of the file’s content, regardless of its size, preventing terminal overflow with excessive output.

Common Pipeline Patterns

Several pipeline patterns involving head have become standard practice in Linux administration:

ls -l | head -n 5

This limits a directory listing to show only the first 5 files.

ps aux | head

This displays information about only the first 10 running processes, rather than potentially hundreds.

grep "error" /var/log/syslog | head

This shows only the first 10 error messages from the system log, providing a quick overview of recent issues.

Redirecting Output

The output from head can be easily redirected to files for storage or further processing:

head -n 50 database.csv > headers_and_samples.csv

This command extracts the first 50 lines of a CSV file (typically including headers and sample data) and saves them to a new file.

For appending to existing files, use the >> operator:

head -n 20 logfile.txt >> summary.txt

This appends the first 20 lines of the log file to an existing summary file.

Creating Complex Data Processing Chains

Head can be an integral part of sophisticated multi-stage pipelines:

cat access.log | grep "404" | sort | uniq -c | sort -nr | head -n 10

This pipeline finds the 10 most common URLs that returned 404 errors in an access log, demonstrating how head can serve as the final filter in a complex data analysis process.

Practical System Administration Examples

System administrators rely heavily on the head command for daily tasks, using it to efficiently extract vital information from various system files without unnecessary overhead.

Log File Analysis

Log files are typically appended with new entries, making the head command useful for examining the oldest entries (using head on rotated logs) or the beginning of error sequences:

head -n 50 /var/log/syslog

This allows administrators to view the initial system messages after boot or after a service restart, often containing crucial startup information.

For investigating specific service issues:

grep "apache" /var/log/syslog | head -n 20

This shows the first 20 Apache-related log entries, which can help identify when issues first began to appear.

File Content Inspection

Configuration files often contain important settings at the beginning, with comments explaining their purpose:

head /etc/nginx/nginx.conf

This command quickly reveals the main configuration settings and initial directives of the Nginx web server.

For script analysis:

head -n 20 /usr/local/bin/custom_script.sh

This displays the script’s shebang line, initial comments, and function definitions, which usually provide information about the script’s purpose and usage.

Data Processing Workflows

When working with data files, head provides a quick way to understand their structure:

head -n 1 dataset.csv

This command shows just the header row of a CSV file, revealing the column names and structure without loading the entire dataset.

For more comprehensive inspection:

head -n 10 large_dataset.tsv | column -t -s $'\t'

This pipeline displays the first 10 lines of a tab-separated data file in a formatted table, making the data structure immediately apparent.

Text File Operations

Extract metadata from document files:

head -n 20 document.md | grep "^#"

This command shows all headings (lines starting with #) from the beginning of a Markdown document, effectively extracting its outline.

Advanced Usage Techniques

Beyond the basics, the head command offers advanced capabilities that experienced Linux users can leverage for more specialized tasks.

Combining Options for Powerful Results

Multiple head options can be combined for more precise control:

head -n 50 -v logfile.txt

This displays the first 50 lines of the log file with the filename header explicitly included.

A more complex example:

head -c 1k -q file1.bin file2.bin | hexdump -C

This extracts the first kilobyte from each of two binary files without headers, then pipes the combined output to hexdump for analysis.

Using Multiplier Suffixes

The byte count option supports various multiplier suffixes for convenience when working with larger data chunks:

head -c 2M large_file.dat

This extracts the first 2 megabytes of data, which is much more convenient than typing head -c 2097152 large_file.dat.

Available suffixes include:

  • b (512-byte blocks)
  • k or K (kilobytes, 1024 bytes)
  • m or M (megabytes, 1024 kilobytes)

Binary File Handling

When examining binary files, combining head with hexdump or xxd provides a structured view of file headers:

head -c 256 /bin/bash | xxd

This displays the first 256 bytes of the bash executable in hexadecimal format, revealing its ELF header and initial binary structure.

Script Integration

Incorporating head into bash scripts allows for automated file processing:

#!/bin/bash
for file in /var/log/*.log; do
    echo "=== First 5 lines of $file ==="
    head -n 5 "$file"
    echo ""
done

This script loops through all log files in /var/log and displays the first 5 lines of each, providing a quick overview of all logs.

Error Handling

When using head in scripts, it’s important to handle potential errors:

if head -n 10 "$file" > /dev/null 2>&1; then
    echo "Successfully read from $file"
    head -n 10 "$file" > output.txt
else
    echo "Error accessing $file" >&2
fi

This script checks if head can successfully read from a file before attempting to process its output, providing proper error handling.

Best Practices and Optimization

Using the head command effectively requires understanding both its capabilities and limitations, as well as how it fits into broader system administration workflows.

Performance Considerations

The head command is designed for efficiency, as it reads only the required portion of files rather than loading them completely:

head -n 10 large_log.txt

This command will complete almost instantly even if large_log.txt is several gigabytes in size, since head stops reading after the 10th line.

When working with extremely large files, prefer byte-limited operations for even greater efficiency:

head -c.10k very_large_file.dat

This approach is faster than line-counting for huge files, as head doesn’t need to scan for newline characters through the entire file.

Command Selection Guidelines

Choose head over other commands when:

  • You only need to examine the beginning of files
  • You want minimal resource usage
  • You’re working with potentially large files
  • You need to process multiple files in sequence

For interactive exploration of files, consider alternatives like less or more instead.

Common Mistakes to Avoid

Avoid using head when you need content from the middle or end of files – tail or sed would be more appropriate. Additionally, be cautious with the byte count option (-c) when working with text files containing multi-byte characters, as it may split characters incorrectly.

Remember that negative values work differently with -n and -c:

head -n -5 file.txt     # All but the last 5 lines
head -c -5 file.txt     # Error: invalid number of bytes

Workflow Optimization Tips

Create aliases for frequently used head commands:

alias logpeek='head -n 25 /var/log/syslog'
alias csvheader='head -n 1'

These aliases can significantly streamline daily administration tasks, reducing typing and ensuring consistent command usage.

Comparison with Related Commands

Understanding how head relates to other text-processing commands helps in selecting the right tool for specific tasks.

Head vs. Tail

While head displays the beginning of files, tail shows the end:

head -n 10 logfile.txt  # First 10 lines
tail -n 10 logfile.txt  # Last 10 lines

Tail also offers the -f option to follow file updates in real-time, which head doesn’t provide. Use head for examining static file beginnings and tail for monitoring ongoing changes.

Head vs. Cat

Cat displays entire files, while head shows only beginnings:

cat file.txt          # Displays entire file
head -n 20 file.txt   # Displays first 20 lines

Use head instead of cat when dealing with large files to prevent overwhelming your terminal with output.

Head vs. Less/More

Less and more are interactive pagers, while head is non-interactive:

less file.txt     # Interactive navigation
head file.txt     # Non-interactive, fixed output

Use head for scripting and quick views, and less/more for manual exploration of larger files.

Head vs. Grep

Grep filters lines by pattern, while head filters by position:

grep "error" log.txt         # Lines containing "error"
head -n 100 log.txt          # First 100 lines
head -n 100 log.txt | grep "error"  # Errors in first 100 lines

Combining both commands creates powerful targeted searches within file beginnings.

Real-world Applications and Case Studies

The head command finds practical applications across various technical domains, demonstrating its versatility beyond simple file previewing.

DevOps Implementation Examples

In continuous integration pipelines, head helps with log analysis:

docker logs container_name | head -n 50 > startup_log.txt

This captures the initial startup messages from a Docker container, crucial for debugging initialization issues.

For automated testing, head can extract relevant test summaries:

./run_tests.sh | head -n 20 | grep "FAILED"

This quickly identifies failing tests from test suite output.

Data Analysis Workflows

Data scientists use head for dataset examination:

head -n 5 dataset.csv

This provides a quick preview of data structure and content without loading entire datasets, which might be gigabytes in size.

For header validation:

head -n 1 dataset1.csv > expected_format.csv
head -n 1 dataset2.csv | diff - expected_format.csv

This approach compares CSV headers against an expected format to ensure consistency before processing.

System Monitoring Solutions

System administrators use head in monitoring scripts:

head -n 50 /var/log/auth.log | grep -i "failed password"

This identifies recent authentication failures, potentially alerting about brute force attempts.

For alert generation:

head -n 1000 /var/log/messages | grep -i "critical" | mail -s "Critical System Alerts" admin@example.com

This pipeline scans recent system messages for critical alerts and emails them to administrators.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button