Linux Commands GuideLinux Tutorials

Mastering the Linux head Command: Quick File Previews and Practical Examples

The Linux head command is an essential tool for system administrators, developers, and anyone working on the command line who needs to preview the beginning of files or piped output quickly. This guide covers the Linux head command in depth: syntax, key options for lines and bytes, handling multiple files, using head in pipelines, platform differences (GNU/Linux vs macOS), and practical usage patterns for logs, scripts, and troubleshooting. Whether you need the first 10 lines by default or the first few bytes for binary inspection, you will learn safe, efficient, and script-friendly ways to integrate head into your daily workflows. The examples are realistic and suitable for Debian, Ubuntu, RHEL/CentOS, and macOS shells.

Syntax, Options and Portability

The basic syntax of head is simple but flexible: head [OPTION]... [FILE].... By default head prints the first 10 lines of each file. The most commonly used options are -n or --lines to control the number of lines and -c or --bytes to request a specific number of bytes. GNU coreutils and BSD implementations (macOS) share most behavior, but small differences exist in suffix multipliers and option parsing. Use head in scripts to avoid loading whole files into memory; it's fast and predictable. Below are practical examples that demonstrate common tasks, including viewing a specific number of lines, reading bytes, combining head with other tools, and inspecting multiple files.

head -n 5 /var/log/syslog

Feb 10 14:22:01 myhost systemd[1]: Starting Daily apt upgrade and clean activities...
Feb 10 14:22:01 myhost systemd[1]: Started Daily apt upgrade and clean activities.
Feb 10 14:22:01 myhost CRON[12345]: (root) CMD (   cd / && run-parts --report /etc/cron.daily)
Feb 10 14:22:02 myhost kernel: [    0.000000] Initializing cgroup subsys cpuset
Feb 10 14:22:02 myhost kernel: [    0.000000] Initializing cgroup subsys cpu

The command prints the first five lines of /var/log/syslog. The -n option controls lines; here 5 is the number requested. This is useful for getting a quick look at recent boot messages or log headers without opening the entire log file.

Display a Specific Number of Lines

To control how many lines head prints use the -n option. You can also use the concise form -NUMBER (e.g., -5). This is handy when inspecting configuration files or when composing scripts that need a deterministic number of lines for parsing. If you provide multiple files, head prints a header with the filename before each block unless told otherwise (GNU head has options to suppress headers with --quiet or -q).

head -n 20 /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
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-network:x:100:102:systemd Network Management:/:/usr/sbin/nologin
systemd-resolve:x:101:103:systemd Resolver:/:/usr/sbin/nologin

Using -n 20 prints the first 20 entries of /etc/passwd. In scripts, combine with cut or awk to extract specific fields from the displayed lines.

Display a Specific Number of Bytes

When you need the first N bytes instead of lines, use the -c option. This is useful when inspecting binary files, headers, or when you need a fixed-size prefix of a file. head supports suffix multipliers (GNU head supports both SI and binary suffixes like kB, K, MB, M, etc.) to express sizes concisely.

head -c 100 /etc/issue

Ubuntu 20.04.3 LTS  \l
Kernel \r on an \m

The command displays the first 100 bytes of /etc/issue; output may contain escape sequences or non-printable characters. The -c flag is ideal for capturing fixed byte-length headers like magic numbers or protocol preambles.

Using Multipliers with Bytes

GNU head accepts suffixes: b (512), kB (1000), K (1024), MB (1,000,000), M (1,048,576). On BSD/macOS, support varies, so prefer explicit byte counts in portable scripts or check your head implementation.

head -c 5K sample.log

[INFO] 2026-03-01 12:00:00 Service started
[INFO] 2026-03-01 12:00:01 Connection from 192.0.2.10
[DEBUG] Init sequence complete
[INFO] 2026-03-01 12:00:02 Health check OK

Here -c 5K requests the first 5 * 1024 bytes (GNU semantics for uppercase K). The output is a truncated chunk of lines that fit in the requested byte limit.

Display Multiple Files and Headers

When you pass multiple files, head prints each file's first lines and prefixes each block with a header line like “==> filename <==". This behavior is helpful when quickly comparing multiple files. If you want to suppress headers in scripting contexts, use –quiet or -q if supported by your head version. For portability, you can call head separately for each file in a loop.

head -n 3 /var/log/auth.log /var/log/dpkg.log

==> /var/log/auth.log <==
Feb 10 13:59:45 myhost sshd[2345]: Accepted password for user1 from 198.51.100.23 port 53116 ssh2
Feb 10 13:59:46 myhost sudo:    user1 : TTY=pts/2 ; PWD=/home/user1 ; USER=root ; COMMAND=/bin/apt update
Feb 10 13:59:47 myhost sshd[2346]: pam_unix(sshd:session): session opened for user user2 by (uid=0)
==> /var/log/dpkg.log <==
2026-02-10 13:54:01 install libc-bin:amd64 2.31-0ubuntu9.9
2026-02-10 13:54:02 status half-configured libc-bin:amd64 2.31-0ubuntu9.9
2026-02-10 13:54:05 status installed libc-bin:amd64 2.31-0ubuntu9.9

Both files are shown with headers to separate outputs. Use -q or a loop to avoid headers when piping results into other tools.

Using head in Pipelines and Scripts

head is frequently used in pipelines to trim output before passing it to other tools. Because head exits after producing requested output, it can reduce data processed by downstream commands. Common uses include sampling command output, generating test data, creating short previews of large files, and extracting deterministic prefixes for checksumming and fingerprinting.

echo $RANDOM | sha512sum | head -c 24 ; echo

1f2d3e4a5b6c7d8e9f0a1b2c

This pipeline generates a SHA-512 hash of a random number and uses head -c 24 to print only the first 24 bytes (characters) of the resulting checksum. The trailing echo ensures a newline. Use this pattern to generate shortened identifiers for temporary filenames or test tokens.

Use Cases: Logs, Configs, and Large Files

head is especially effective for examining log files, configuration headers, or any file where you only need the top portion. Common administrative tasks include: verifying file format, confirming the timestamp or header information, quickly checking config files for syntax markers at the top, and sampling large CSVs or JSON files before performing costly parsing. Use head together with tail, sed, awk, and grep to inspect and transform data efficiently.

head -n 1 /etc/cron.daily/apt-compat

#!/bin/sh

Inspecting the first line of a script confirms the interpreter declaration (shebang). This is a quick check to ensure the script will run as intended and can be automated in compliance checks.

Portability and Caveats

Most modern Linux distributions use GNU coreutils head, while macOS uses the BSD variant. Differences to watch for: suffix interpretations for byte multipliers, and some long options (like --verbose, --quiet) might differ. When writing scripts intended to run across platforms, prefer explicit numeric arguments and avoid relying on implementation-specific behavior. Also be cautious when reading from named pipes or devices—head will exit once it has produced the requested count, which might leave producers waiting if not properly coordinated.

head -n 1 /dev/urandom

x

Reading from /dev/urandom with -n 1 returns a single line—likely containing non-printable bytes—so output may appear garbled. Use -c when you need exact byte counts from binary devices.

Combining head and tail for Ranged Views

If you need lines from the middle of a file, combine head and tail: head to get the first N lines, then tail to extract the last M of those. This technique avoids loading whole files in memory and is efficient for large data sets.

head -n 100 large.log | tail -n 20

[INFO] 2026-03-01 14:00:21 Task completed successfully
[WARN] 2026-03-01 14:01:02 Disk utilization 85%
[INFO] 2026-03-01 14:01:05 New connection established
[ERROR] 2026-03-01 14:01:07 Failed to open /var/lib/app/state

This command prints lines 81–100 by first taking the first 100 lines with head -n 100 and then the last 20 of that group with tail -n 20. It’s a common pattern for extracting a specific slice of a file when sed or awk are not desired.

Exit Codes and Error Handling

head returns an exit status of 0 on success. Non-zero statuses indicate issues such as missing files or read errors. When using head in scripts, always check the exit code ($?) and consider adding defensive checks (test -r file) before invoking head on important resources.

head -n 10 missing.file

head: cannot open 'missing.file' for reading: No such file or directory

If head cannot open a file, it prints an error to stderr and exits with a non-zero code. Use shell conditionals to handle such cases in automation.

Conclusion

The Linux head command is a lightweight, dependable utility for previewing file contents and controlling the amount of data passed through pipelines. Mastering head helps reduce unnecessary data processing, speeds up troubleshooting, and simplifies scripting tasks across distributions. Remember to choose between -n for lines and -c for bytes, watch portability between GNU and BSD variants, and combine head with other Unix tools for powerful, readable one-liners. With the patterns shown above, you can confidently use head for logs, configs, binary inspection, and script-friendly data sampling.

One Comment

  1. Nice guide — the head command examples are really clear; could you add an example showing –bytes (-c) or combining head with process substitution for large/binary files?

Komentariši

Vaša email adresa neće biti objavljivana. Neophodna polja su označena sa *