FIELD NOTES / UNIX & LINUXNew tools on weekdays. Beyond the man page.
$head

head: know what the first part can—and cannot—prove

Bound a view by lines, bytes, or records without confusing a convenient prefix with a complete or representative result.

THE DEEP DIVE13 MIN READ
01

Start with a known prefix

Head copies the beginning of each named file to standard output. With no filename, it reads standard input. It is a standalone utility, not a Bash built-in, and its default boundary is ten newline-delimited lines. It does not sample, sort, parse, or validate those lines: the file's existing order decides what “first” means.

Create a disposable directory for the examples. The commands below make five top-level fixture files plus a names directory containing three empty files, then leave them in place. If head-lab already exists, choose another name. Every setup step is joined with &&, so a failed directory creation or write stops the remaining redirects instead of spilling files into the caller's directory. The shell's > operator creates or replaces a file. In printf, %s inserts each following string and \n appends a newline; the backslash at the end of a command line continues the same command on the next display line. The printf commands that write utf8.txt and response.bin use octal escapes to create exact UTF-8 and binary bytes. Each printf '' emits no bytes, while its > redirection creates the named empty file under names. Later examples run from head-lab.

The final command gives head one filename and no options.

TERMINALSETUP AND COMMAND
mkdir head-lab &&
cd head-lab &&
printf '%s\n' \
  '2026-10-19T08:00:00Z INFO api ready' \
  '2026-10-19T08:01:00Z INFO worker ready' \
  '2026-10-19T08:02:00Z WARN queue depth=7' \
  '2026-10-19T08:03:00Z INFO health ok' \
  '2026-10-19T08:04:00Z ERROR login failed user=alex' \
  '2026-10-19T08:05:00Z INFO retry accepted' \
  '2026-10-19T08:06:00Z WARN disk 81%' \
  '2026-10-19T08:07:00Z INFO rotation start' \
  '2026-10-19T08:08:00Z INFO rotation done' \
  '2026-10-19T08:09:00Z ERROR token rejected user=sam' \
  '2026-10-19T08:10:00Z INFO cache warm' \
  '2026-10-19T08:11:00Z WARN queue depth=9' > events.log &&
printf '%s\n' \
  '2026-10-19T08:00:30Z ACCEPT user=alex' \
  '2026-10-19T08:04:30Z REJECT user=alex' \
  '2026-10-19T08:07:30Z ACCEPT user=sam' \
  '2026-10-19T08:09:30Z REJECT user=sam' > auth.log &&
printf '%s\n' 'WARN source delayed' 'ERROR source unavailable' 'INFO source restored' > ./-alerts.log &&
printf '\303\251clair\n' > utf8.txt &&
printf '\033[31mALERT\000token=demo\n' > response.bin &&
mkdir names &&
printf '' > 'names/alpha report' &&
printf '' > 'names/line
break' &&
printf '' > 'names/zeta' &&
head events.log
TERMINALEXPECTED OUTPUT
2026-10-19T08:00:00Z INFO api ready
2026-10-19T08:01:00Z INFO worker ready
2026-10-19T08:02:00Z WARN queue depth=7
2026-10-19T08:03:00Z INFO health ok
2026-10-19T08:04:00Z ERROR login failed user=alex
2026-10-19T08:05:00Z INFO retry accepted
2026-10-19T08:06:00Z WARN disk 81%
2026-10-19T08:07:00Z INFO rotation start
2026-10-19T08:08:00Z INFO rotation done
2026-10-19T08:09:00Z ERROR token rejected user=sam

Events.log contains twelve lines, but the default result stops after ten. That bounded view is useful for orientation. It is not evidence that the last two records are unimportant, that no later error exists, or that these ten records represent the file as a whole.

02

Choose the count, and protect an odd filename

Use -n when the number of lines is part of the question. The 3 is the argument to -n, so the first command copies three newline-delimited lines instead of the default ten.

The second command asks for two lines from a file whose name begins with a hyphen. The standalone -- ends head's option parsing; everything after it is treated as an operand rather than another option. The ./ prefix used during setup also prevents that pathname from beginning with a hyphen, but -- is the general option-boundary convention used here.

TERMINALSHELL
head -n 3 events.log
head -n 2 -- -alerts.log
TERMINALEXPECTED OUTPUT
2026-10-19T08:00:00Z INFO api ready
2026-10-19T08:01:00Z INFO worker ready
2026-10-19T08:02:00Z WARN queue depth=7
WARN source delayed
ERROR source unavailable

The outputs are adjacent because both commands write to the same standard output. Head does not add a label when it receives only one file. A script that combines several prefixes needs to preserve attribution deliberately.

03

Keep several prefixes attributable

When GNU head receives more than one file, it normally prints a header before each file's output. Here -n 2 applies separately to both files, not to their combined stream.

The -q flag, also spelled --quiet, suppresses filename headers. The -v flag, also spelled --verbose, forces a header even when only one file is named. Suppression can make output compact, but it also removes provenance.

TERMINALSHELL
head -n 2 events.log auth.log
head -q -n 1 events.log auth.log
head -v -n 1 events.log
TERMINALEXPECTED OUTPUT
==> events.log <==
2026-10-19T08:00:00Z INFO api ready
2026-10-19T08:01:00Z INFO worker ready

==> auth.log <==
2026-10-19T08:00:30Z ACCEPT user=alex
2026-10-19T08:04:30Z REJECT user=alex
2026-10-19T08:00:00Z INFO api ready
2026-10-19T08:00:30Z ACCEPT user=alex
==> events.log <==
2026-10-19T08:00:00Z INFO api ready

The quiet command's two records have no source labels; only their content hints at origin. Keep the default headers or add another reliable identifier when records from different files can look alike.

04

Make the order answer the question

Head preserves stream order. It does not know that an ISO-style timestamp is a time or that the latest event may matter more than the earliest one. Because every events.log line begins with a fixed-width timestamp, bytewise reverse sorting puts the latest timestamp first in this controlled fixture.

LC_ALL=C applies the C locale to sort for this command, making bytewise order explicit. Sort's -r flag reverses the result. The shell's | operator connects sort's standard output to head's standard input; head receives no filename and takes the first three lines of that new order. The sort deep dive explains why ordering rules and key choices determine which records compare as equal or first.

TERMINALSHELL
LC_ALL=C sort -r events.log | head -n 3
TERMINALEXPECTED OUTPUT
2026-10-19T08:11:00Z WARN queue depth=9
2026-10-19T08:10:00Z INFO cache warm
2026-10-19T08:09:00Z ERROR token rejected user=sam

This returns the latest three timestamps only because the fixture's timestamp format sorts chronologically as text. Sorting the whole input also does more work than reading an existing prefix. For a live stream, a rotated log set, or timestamps with mixed formats, establish the real ordering contract before calling the result “latest.”

05

A byte boundary can split a character

Line limits preserve newline-delimited records. Byte limits answer a different question: how much raw data may pass. In GNU head, the -c flag selects a byte count, so -c 1 copies one byte and -c 2 copies two. POSIX head does not specify -c, even though other implementations may also provide it. Utf8.txt begins with é, encoded in this fixture as the two UTF-8 bytes c3 a9.

The first pipeline sends the one-byte prefix to wc -c, which reports how many bytes arrived without trying to display the incomplete character. The wc deep dive develops the distinction among bytes, characters, lines, and display width. The second head copies both bytes; the following printf supplies a newline because that two-byte prefix does not include the file's newline.

TERMINALSHELL
head -c 1 utf8.txt | wc -c
head -c 2 utf8.txt
printf '\n'
TERMINALEXPECTED OUTPUT
1
é

Head -c counts bytes, not Unicode characters. A byte bound is appropriate for protocol prefixes, storage limits, and controlled inspection, but it can produce invalid text. Do not send an incomplete or unknown byte sequence straight to a terminal and assume the display proves what the bytes were.

06

Count NUL-delimited pathname records

A newline is legal inside a Unix filename, so line-based head can split a pathname list. GNU head's -z flag, also spelled --zero-terminated, changes the item delimiter from newline to the NUL byte. NUL cannot occur inside a Unix pathname.

GNU find selects entries below names. The -mindepth 1 option excludes the starting directory itself, -maxdepth 1 prevents descent below its immediate children, and -type f keeps only regular files. Its -printf '%P\0' writes each pathname relative to names followed by NUL. The find article explains selection and NUL-safe output. GNU sort -z orders the same NUL-delimited records under the C locale. Head -z -n 2 then copies two whole records. Od renders the result safely: -A n suppresses address offsets, while -t x1 displays each byte as a two-digit hexadecimal value.

TERMINALGNU/LINUX SHELL
find names -mindepth 1 -maxdepth 1 -type f -printf '%P\0' |
  LC_ALL=C sort -z |
  head -z -n 2 |
  od -A n -t x1
TERMINALEXPECTED HEX BYTES
 61 6c 70 68 61 20 72 65 70 6f 72 74 00 6c 69 6e
 65 0a 62 72 65 61 6b 00

The first 00 ends alpha report. The second record contains 0a, a newline byte, between line and break; head does not split there because -z makes 00 the boundary. The final 00 completes that pathname. A compatible downstream consumer such as xargs -0 can read these records; the xargs article explains that handoff. The -z behaviors of head and sort and find's -printf are GNU features, not a portable assumption about every Unix implementation.

07

Define a prefix from the far end

GNU head accepts a negative argument to -n. In -n -2, the first -n selects line-count mode and the separate -2 is its argument: output everything except the final two lines. The shell does not perform subtraction here.

This is useful for removing a fixed trailer without first calculating the line count. GNU head can still emit older records while retaining a rolling two-line suffix, but it cannot finish or know that the retained records are truly final until it reaches end of input.

TERMINALGNU HEAD
head -n -2 events.log
TERMINALEXPECTED OUTPUT
2026-10-19T08:00:00Z INFO api ready
2026-10-19T08:01:00Z INFO worker ready
2026-10-19T08:02:00Z WARN queue depth=7
2026-10-19T08:03:00Z INFO health ok
2026-10-19T08:04:00Z ERROR login failed user=alex
2026-10-19T08:05:00Z INFO retry accepted
2026-10-19T08:06:00Z WARN disk 81%
2026-10-19T08:07:00Z INFO rotation start
2026-10-19T08:08:00Z INFO rotation done
2026-10-19T08:09:00Z ERROR token rejected user=sam

The twelve-line file becomes a ten-line prefix by withholding the last two lines. This negative-count form is documented by GNU coreutils; POSIX scripts should not assume it is present. On an endless input, GNU head can keep emitting earlier records, but it never completes and always withholds the newest two because there is no end at which to identify a final pair.

08

An intentional early close can look like failure

A positive limit can let head finish while the producer still has data to write. Yes repeatedly emits probe; head copies three lines to standard output and closes its end of the pipe. A pipe is a byte stream, so head may read a larger buffer than it ultimately outputs. The parenthesized producer runs in a subshell. There, trap '' PIPE tells Bash to ignore SIGPIPE, and yes inherits that signal disposition. When head closes the pipe, GNU yes therefore sees the EPIPE write error and returns status 1 instead of being terminated by SIGPIPE. The producer's 2>/dev/null redirection keeps its expected broken-pipe diagnostic out of this controlled display. Immediately after each pipeline, Bash's PIPESTATUS array contains the component statuses.

The special parameter $? is the status of the immediately preceding pipeline. Bash's PIPESTATUS array holds one status for each command in that pipeline, and ${PIPESTATUS[@]} expands all of its elements. The compound assignment pipeline=$? parts=("${PIPESTATUS[@]}") expands those values before the assignment command replaces them: pipeline receives the overall pipeline status, while parts receives the component statuses. In the later printf, ${parts[0]} is the producer-subshell status, ${parts[1]} is the consumer head status, and quoted $pipeline is the saved overall status. By default, Bash uses the final command's status for a pipeline. The outer parentheses around the second sequence create another subshell, and set -o pipefail changes only that scope: the pipeline then returns the rightmost nonzero component status.

TERMINALBASH 5.2
( trap '' PIPE; yes probe ) 2>/dev/null | head -n 3
pipeline=$? parts=("${PIPESTATUS[@]}")
printf 'producer=%s head=%s pipeline=%s\n' "${parts[0]}" "${parts[1]}" "$pipeline"

( set -o pipefail
  ( trap '' PIPE; yes probe ) 2>/dev/null | head -n 3
  pipeline=$? parts=("${PIPESTATUS[@]}")
  printf 'producer=%s head=%s pipeline=%s\n' "${parts[0]}" "${parts[1]}" "$pipeline"
)
TERMINALOBSERVED OUTPUT
probe
probe
probe
producer=1 head=0 pipeline=0
probe
probe
probe
producer=1 head=0 pipeline=1

With SIGPIPE explicitly ignored in the producer subshell, GNU coreutils 9.4 yes reports status 1 after head closes the pipe; head reports 0. Without that explicit trap, producers and execution contexts can expose a closed pipe differently, including termination by SIGPIPE, so status 1 is not a general portable rule. With pipefail, expected truncation can make a script's pipeline nonzero. Check whether the requested prefix arrived and why the producer stopped before classifying that status as data failure.

09

Inspect an unfamiliar prefix without rendering it

During an authorized assessment or incident review, a small prefix can help triage a supplied artifact before a full parser touches it. Raw bytes can include terminal control sequences, so bounding the read is only half the job; the representation must also be safe.

The synthetic response.bin begins with the escape byte 1b and the ASCII bytes for [31mALERT, followed by NUL and more text. Head -c 16 sends only its first sixteen bytes to od. The already introduced -A n and -t x1 options render those bytes as hexadecimal instead of terminal instructions.

TERMINALSHELL
head -c 16 response.bin | od -A n -t x1
TERMINALEXPECTED HEX BYTES
 1b 5b 33 31 6d 41 4c 45 52 54 00 74 6f 6b 65 6e

The prefix confirms the controlled fixture starts with an escape sequence and contains ALERT, but it does not identify or authenticate the whole artifact, prove that later bytes are harmless, or make an unsafe downstream parser safe. Keep the original evidence and use format-specific tooling when the question moves beyond bounded triage.

10

Choose a bound you can defend

Before relying on head, ask four questions. Is the existing order meaningful for the decision? Is a line, byte, or NUL-terminated item the real record boundary? Can the selected boundary split text or structured data? Will an upstream producer's early termination be expected, hidden, or treated as an error?

Head is dependable when the claim stays as narrow as the command: these are the first N units of this particular ordered input. It becomes misleading when “first” quietly turns into “representative,” “latest,” “complete,” or “safe.”

Back to latest issue
HELP SHAPE THE NEXT ISSUE

What belongs in your toolbox?

Choose a command you want to know better. We start with familiar tools and work toward the less obvious ones.

READER’S CHOICE

What should we cover next?

Vote for a future deep dive, or suggest a command we missed.

One command name, up to 32 characters. Suggestions are reviewed by a person. A new article starts a fresh poll.

Loading poll…