Skip to content

Latest commit

 

History

History
198 lines (134 loc) · 7.14 KB

File metadata and controls

198 lines (134 loc) · 7.14 KB
title Linux Command Tutorial: head
date 2026-09-12 00:00:00 +0000
categories
Technology
tags
Linux
GNU Coreutils
head
Linux Command Tutorial
draft false
slug linux-head-tutorial
description Authoritative reference tutorial for head (GNU Coreutils), detailing line and byte slicing, negative offset indexing, null delimiter parsing, and POSIX portability.
upstream_suite gnu-coreutils
upstream_version GNU Coreutils 9.11
posix_standard POSIX.1-2024
research_date 2026-09-12

The Linux Command Tutorial series provides rigorous, upstream-verified references for essential system commands across Linux distributions and UNIX-like environments. Each article focuses on a single executable, combining exhaustive option documentation, verified real-world examples, security boundaries, and best practices directly derived from official source documentation and POSIX standards.


1. Introduction

Upstream: GNU Coreutils 9.11 | POSIX: POSIX.1-2024 (with GNU extensions) | Safety Tier: safe-read-only | Scope: Stream prefix extraction, line & byte slicing & pipeline bounding

head outputs the beginning portion (the first N lines or bytes) of specified files or standard input. When given multiple input files, head prints headers preceding each file's output.

  • Upstream Project & Provenance: Distributed in GNU Coreutils (coreutils).
  • Portability & Standards Baseline: Standardized in IEEE Std 1003.1-2024 (POSIX.1-2024). GNU head adds negative indexing (-n -K), byte slicing units (K, M, G), and null delimiter support (-z).
  • Target Research Implementation: Audited against GNU Coreutils 9.11 (head(1)).
  • Applicability & Lifecycle: The standard command for inspecting data headers, extracting prefixes, and preventing terminal buffer flooding.

2. Syntax and Command Model

2.1 Canonical Synopsis

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

2.2 Execution Model & Default Quantities

  • Defaults to outputting the first 10 lines when invoked without parameters.
  • When reading from a pipe or file, head exits immediately upon reaching the requested line or byte count, closing its input pipe and sending SIGPIPE to any upstream producer.

3. Options

3.1 Primary Operational Flags

Short Flag Long Flag Description POSIX Defined Default
-n K --lines=[-]K Print first K lines; with leading -, print all but the last K lines. Yes (positive only) 10
-c K --bytes=[-]K Print first K bytes; with leading -, print all but the last K bytes. Yes (positive only) N/A
-q --quiet, --silent Never print headers giving file names. No Multi-file auto
-v --verbose Always print headers giving file names. No Off
-z --zero-terminated Line delimiter is NUL (\0), not newline. No Off

4. Basic Usage

4.1 Quick Reference & Common Invocations

Task / Scenario Command Key Flags / Behavior
First 10 lines (default) head /var/log/syslog Outputs first 10 lines of file
First N lines explicitly head -n 25 /var/log/nginx/access.log -n 25 limits output to 25 lines
First N bytes head -c 64 file.bin -c 64 limits output to first 64 bytes
All lines except last N head -n -5 dataset.csv Negative count prints all but last 5 lines
Suppress file header banners head -q -n 5 file1 file2 -q hides ==> file <== headers
Null-delimited stream prefix find . -print0 | head -z -n 5 -z handles null-separated entries

4.2 First 10 Lines (Default)

head /var/log/syslog

4.3 First 5 Lines Explicitly

head -n 5 /etc/passwd

5. Practical Operations

5.1 Extracting Binary Headers by Byte Count

Inspecting the first 16 bytes of an unknown image file to check its magic bytes:

head -c 16 firmware.bin | xxd

Sample terminal output:

00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000  .ELF............
  • Technical Analysis: -c 16 reads exactly 16 bytes and halts, preventing huge binary files from dumping into the terminal.

5.2 Negative Line Offsets: Slicing "All Except the Last N Lines"

Extracting a CSV dataset while removing a 2-line summary footer at the end of the file:

head -n -2 raw_metrics.csv > clean_metrics.csv
  • Technical Analysis: The -n -2 syntax is a GNU Coreutils feature that outputs every line from the start of the file up to, but excluding, the last 2 lines.

5.3 Multiple File Inspection with Headers

head -n 2 /etc/hosts /etc/resolv.conf

Sample terminal output:

==> /etc/hosts <==
127.0.0.1 localhost
::1 localhost ip6-localhost

==> /etc/resolv.conf <==
nameserver 127.0.0.53
options edns0 trust-ad

6. Advanced Usage

6.1 Safe Null-Delimited Traversal with -z

Parsing zero-terminated streams generated by find -print0:

find /var/log -type f -print0 | head -z -n 3 | xargs -0 ls -l
  • Operates safely on files containing embedded newlines or spaces.

7. Exit Status, Environment, and Configuration

7.1 Exit Status Codes

Exit Code Meaning
0 Success: requested prefix was output cleanly.
>0 An error occurred (input file unreadable, invalid byte/line count).

8. Safety, Security, and Portability

8.1 SIGPIPE Upstream Termination

Warning

Pipeline Broken Pipe (SIGPIPE) Hazard: When head -n 10 finishes reading 10 lines from a pipeline, it immediately exits and closes standard input. If an upstream producer attempts to write more data into the closed pipe, the kernel sends SIGPIPE (signal 13).

In shell scripts configured with set -e and set -o pipefail, this causes the entire script to abort with exit code 141 (128 + 13). Handle or expect SIGPIPE in large generation pipelines.

8.2 Negative Indexing Portability

Note

The negative count syntax (head -n -K and head -c -K) is a GNU Coreutils extension. POSIX.1-2024 and BSD/macOS implementations of head reject negative arguments with syntax errors.


9. Best Practices

  1. Use -n <count> with Pipelines to Limit Terminal Flooding:

    [!TIP] Guidance: Pipe unfamiliar commands into head -n 20. Authoritative Justification: Prevents gigabytes of output from scrolling off terminal buffers and saturating display renderers.

  2. Use -n -K Instead of Heavyweight Sed Footers:

    [!TIP] Guidance: Strip file footers using head -n -K in shell scripts. Authoritative Justification: GNU Coreutils provides optimized streaming buffers for negative indexing without invoking heavyweight regex interpreters.


References

  1. GNU Coreutils head Manual: https://www.gnu.org/software/coreutils/manual/html_node/head-invocation.html
  2. POSIX.1-2024 head Specification: The Open Group Base Specifications Issue 8. https://pubs.opengroup.org/onlinepubs/9799919799/utilities/head.html