LinuxCommandLibrary

head

Display the beginning of a file

TLDR

Output the first few lines of a file

$ head -n [count] [path/to/file]
copy

SYNOPSIS

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

PARAMETERS

-c, --bytes=[-]K
    print the first K bytes (default: 10 lines); leading - prints all but last K bytes; K can have suffix (kB, MB, etc.)

-n, --lines=[-]K
    print the first K lines instead of 10; leading - prints all but last K lines

-q, --quiet, --silent
    suppress printing filename headers

-v, --verbose
    always print filename headers, even for one file

-z, --zero-terminated
    delimit lines by NUL instead of newline

--help
    display help and exit

--version
    output version info and exit

DESCRIPTION

The head command is a fundamental Unix/Linux utility for outputting the initial portion of files or standard input. By default, it prints the first 10 lines of each specified file to stdout, making it ideal for quick previews of logs, scripts, or data files without processing everything.

Key strengths include precise control over output size via lines (-n) or bytes (-c), support for multiple files with optional headers, and efficiency on large files—it stops reading early. For pipelines, it's common in commands like ps aux | head -5 to limit results or head -n1 access.log for the latest entry.

When reading stdin (no files or -), it behaves similarly. Headers like ==> filename <= appear for multiple files unless quiet mode is used. It's POSIX-compliant, portable across systems, and pairs well with tools like grep or sort for data inspection.

CAVEATS

Inefficient for very large files if outputting many lines/bytes; assumes text input (binary may truncate oddly); no built-in pattern matching—use with grep.

COMMON EXAMPLES

head file.txt
Print first 10 lines.

head -n 5 /var/log/syslog
First 5 lines of log.

curl example.com | head -c 100
First 100 bytes from URL.

head -n -1 data.csv
All but last line.

HISTORY

Originated in AT&T System III Unix (1980); standardized in POSIX.1-2001; GNU coreutils version since 1990s adds byte output, multipliers, and NUL delimiter.

SEE ALSO

tail(1), cat(1), tac(1), sed(1)

Copied to clipboard