The head Command: Complete Guide and Reference
Overview
The head command is a fundamental Unix/Linux utility that displays the first part of files. By default, it shows the first 10 lines of one or more files, making it an essential tool for quickly previewing file contents, examining log files, or inspecting data without opening the entire file in an editor.
The command is particularly useful when working with large files where you only need to see the beginning portion, such as configuration files, log files, or data files with headers.
Basic Syntax
`bash
head [OPTION]... [FILE]...
`
Where:
- OPTION represents various command-line flags and parameters
- FILE represents one or more files to process
If no file is specified, head reads from standard input, making it useful in command pipelines.
Command Options and Parameters
| Option | Long Form | Description | Example |
|--------|-----------|-------------|---------|
| -n NUM | --lines=NUM | Display first NUM lines | head -n 5 file.txt |
| -c NUM | --bytes=NUM | Display first NUM bytes | head -c 100 file.txt |
| -q | --quiet, --silent | Suppress headers when multiple files | head -q file1.txt file2.txt |
| -v | --verbose | Always show headers | head -v file.txt |
| -z | --zero-terminated | Line delimiter is NUL, not newline | head -z file.txt |
| --help | | Display help information | head --help |
| --version | | Display version information | head --version |
Basic Usage Examples
Default Behavior
`bash
head filename.txt
`
This displays the first 10 lines of filename.txt. If the file contains fewer than 10 lines, all lines are displayed.
Specifying Number of Lines
`bash
Show first 5 lines
head -n 5 filename.txtAlternative syntax (deprecated but still works)
head -5 filename.txtShow first 20 lines
head -n 20 filename.txt`Working with Bytes Instead of Lines
`bash
Show first 50 bytes
head -c 50 filename.txtShow first 1KB
head -c 1024 filename.txtShow first 1MB
head -c 1M filename.txt`Advanced Usage Scenarios
Multiple Files
When processing multiple files, head displays a header showing the filename before each file's content:
`bash
head file1.txt file2.txt file3.txt
`
Output format:
`
==> file1.txt <==
[first 10 lines of file1.txt]
==> file2.txt <== [first 10 lines of file2.txt]
==> file3.txt <==
[first 10 lines of file3.txt]
`
Suppressing Headers
`bash
Suppress headers when viewing multiple files
head -q file1.txt file2.txtForce headers even for single file
head -v file.txt`Using with Standard Input
`bash
From command pipeline
cat largefile.txt | head -n 15From command substitution
echo "$(ls -la)" | head -n 5Direct input (Ctrl+D to end)
head -n 3`Practical Examples and Use Cases
Log File Analysis
`bash
Check the beginning of system logs
head /var/log/syslogView first 50 lines of Apache access log
head -n 50 /var/log/apache2/access.logQuick check of error logs
head -n 20 /var/log/apache2/error.log`Configuration File Inspection
`bash
Check configuration file headers
head /etc/ssh/sshd_configView first part of hosts file
head /etc/hostsExamine crontab entries
head /etc/crontab`Data File Processing
`bash
View CSV file headers
head -n 1 data.csvCheck first few records of a data file
head -n 5 dataset.txtExamine file structure
head -c 200 binary_file.dat`Development and Debugging
`bash
Check source code file beginning
head -n 30 script.pyView README files
head README.mdCheck build logs
head build.log`Combining with Other Commands
Pipeline Operations
| Command Combination | Purpose | Example |
|-------------------|---------|---------|
| head + tail | Extract middle section | head -n 100 file.txt \| tail -n 10 |
| head + grep | Search in first lines | head -n 50 log.txt \| grep "ERROR" |
| head + sort | Sort first lines | head -n 20 data.txt \| sort |
| head + wc | Count in first lines | head -n 100 file.txt \| wc -w |
| head + awk | Process first lines | head -n 10 data.csv \| awk -F',' '{print $1}' |
Complex Pipeline Examples
`bash
Find most recent log entries and search for errors
head -n 1000 /var/log/syslog | grep -i error | tail -n 5Process CSV headers and first data rows
head -n 11 data.csv | awk -F',' 'NR==1{print "Headers:", $0} NR>1{sum+=$3} END{print "Sum:", sum}'Monitor file changes
watch "head -n 20 growing_file.log"Compare file beginnings
diff <(head -n 10 file1.txt) <(head -n 10 file2.txt)`File Type Considerations
Text Files
`bash
Regular text files
head document.txtCode files
head -n 25 script.shConfiguration files
head config.ini`Binary Files
`bash
View binary file beginning (may show garbled text)
head -c 100 image.jpgExamine executable headers
head -c 50 /bin/ls`Special Files
`bash
Device files (use with caution)
head -c 20 /dev/urandomProcess information
head /proc/cpuinfo head /proc/meminfo`Error Handling and Troubleshooting
Common Errors and Solutions
| Error Message | Cause | Solution |
|---------------|-------|----------|
| head: cannot open 'file' for reading: No such file or directory | File doesn't exist | Check file path and name |
| head: cannot open 'file' for reading: Permission denied | Insufficient permissions | Use sudo or change file permissions |
| head: invalid number of lines: 'abc' | Invalid numeric argument | Use valid numbers only |
| head: invalid number of bytes: '10x' | Invalid byte specification | Use valid byte specifications |
Permission Issues
`bash
Check file permissions
ls -la filename.txtUse sudo for system files
sudo head /var/log/auth.logChange permissions if owned
chmod +r filename.txt`File Encoding Issues
`bash
Handle different encodings
head file.txt | iconv -f ISO-8859-1 -t UTF-8Check file type
file filename.txt`Performance Considerations
Large Files
The head command is highly efficient for large files because it stops reading after reaching the specified number of lines or bytes:
`bash
Efficient for multi-GB files
head -n 10 huge_logfile.logMemory usage remains constant regardless of file size
head -c 1024 10GB_file.dat`Network Files
`bash
Works with mounted network filesystems
head /mnt/nfs/remote_file.txtCan be slow over network connections
head -n 100 /network/path/file.txt`System Integration
Shell Scripting
`bash
#!/bin/bash
Check if file has header
if head -n 1 data.csv | grep -q "Name,Age,City"; then echo "CSV file has proper header" # Process data starting from line 2 tail -n +2 data.csv | while read line; do echo "Processing: $line" done fiFunction to preview files
preview_file() { local file="$1" local lines="${2:-10}" if [[ -f "$file" ]]; then echo "Preview of $file (first $lines lines):" head -n "$lines" "$file" else echo "File not found: $file" fi }`Monitoring Scripts
`bash
#!/bin/bash
Log monitoring script
LOG_FILE="/var/log/application.log" LINES_TO_CHECK=50Check for recent errors
if head -n $LINES_TO_CHECK "$LOG_FILE" | grep -q "ERROR"; then echo "Errors found in recent log entries" head -n $LINES_TO_CHECK "$LOG_FILE" | grep "ERROR" fi`Comparison with Related Commands
| Command | Primary Use | Key Difference |
|---------|-------------|----------------|
| head | Show file beginning | Shows first N lines/bytes |
| tail | Show file end | Shows last N lines/bytes |
| cat | Display entire file | Shows complete file content |
| less/more | Interactive viewing | Paginated, interactive display |
| sed | Stream editing | Can extract any range of lines |
When to Use Each
`bash
Use head for: Quick file preview, checking headers, log analysis
head -n 5 config.txtUse tail for: Recent log entries, file monitoring
tail -f /var/log/syslogUse cat for: Small files, concatenation
cat short_file.txtUse less for: Interactive browsing of large files
less large_document.txt`Best Practices
Security Considerations
1. File Permissions: Always verify you have appropriate permissions
2. Binary Files: Be cautious with binary files in terminals
3. System Files: Use sudo judiciously for system files
4. Input Validation: Validate numeric arguments in scripts
`bash
Safe practices
if [[ -r "$filename" ]]; then head "$filename" else echo "Cannot read file: $filename" fi`Performance Optimization
1. Use appropriate line/byte counts: Don't request more data than needed 2. Combine operations efficiently: Use pipelines wisely 3. Consider file types: Different approaches for text vs binary files
`bash
Efficient: Only read what you need
head -n 5 huge_file.txt | grep "pattern"Less efficient: Read more than necessary
head -n 1000 huge_file.txt | grep "pattern" | head -n 5`Script Integration
`bash
Robust error handling
process_file_header() { local file="$1" local num_lines="${2:-10}" if [[ ! -f "$file" ]]; then echo "Error: File '$file' not found" >&2 return 1 fi if [[ ! -r "$file" ]]; then echo "Error: Cannot read file '$file'" >&2 return 1 fi if ! [[ "$num_lines" =~ ^[0-9]+$ ]]; then echo "Error: Invalid line count '$num_lines'" >&2 return 1 fi head -n "$num_lines" "$file" }`Platform Differences
GNU vs BSD Versions
| Feature | GNU (Linux) | BSD (macOS) | Notes | |---------|-------------|-------------|-------| | Basic functionality | Same | Same | Core features identical | | Long options | Supported | Limited | GNU has more long options | | Byte suffixes | K, M, G, etc. | Limited | GNU supports more suffixes | | Error messages | Detailed | Basic | GNU typically more verbose |
Cross-Platform Scripts
`bash
Detect system type
if head --version 2>/dev/null | grep -q "GNU"; then # GNU version head --lines=10 file.txt else # Assume BSD version head -n 10 file.txt fi`The head command remains one of the most essential and frequently used utilities in Unix-like systems, providing a simple yet powerful way to examine file beginnings efficiently. Its integration with other command-line tools makes it indispensable for system administration, data processing, and general file management tasks.