CMP Meaning in Linux: Compare Files

CMP Meaning in Linux: Compare Files

Comparing files on Linux shows whether their contents match. The cmp command compares two files byte by byte and reports the first place they differ.

I’ll explain what cmp means on Linux and show how to compare files with it.

TL;DR: What cmp means on Linux

On Linux, cmp is a command that compares two files byte by byte and reports the first place they differ. It prints nothing when they match, and its exit status tells a script whether they are equal.

  • Run cmp FILE1 FILE2 for the first difference.
  • Use cmp -l FILE1 FILE2 to list differing byte positions and values.
  • Use cmp -s FILE1 FILE2 when only the exit status matters.
  • Status 0 means same, 1 means different, and 2 means trouble in GNU cmp.

What does cmp mean in Linux?

GNU cmp belongs to diffutils. It reads two input streams in order and compares corresponding bytes until a mismatch or end of input.

Here, cmp means the Linux file-comparison utility. It checks exact bytes rather than interpreting a file’s contents as words, records, or images.

QuestionTool or optionWhat it tells you
Are the files identical?cmp -sExit status only
Where is the first mismatch?cmpFirst differing byte and line
Which bytes differ?cmp -lPositions and byte values
Which text lines changed?diffLine-oriented change report

A byte is a unit of stored data, and files are made up of bytes. Text files can look alike in an editor while differing in a newline, an encoding marker, or a trailing space. cmp catches those byte-level distinctions.

For text files, cmp reports the first mismatch location. A line-oriented tool can show the surrounding edit when a reader needs to understand the change.

I use cmp for an exact file check because its first-mismatch report identifies the offset to investigate.

How to compare files with cmp step by step

Start with the default cmp command because its output shows the first mismatch before you decide whether to list more byte details.

Step 1: Find the first difference

Pass the two filenames to cmp. The first name is FILE1 and the second is FILE2. These labels appear in the diagnostic, so keep the operand order stable when comparing an original with a candidate.

cmp sample-left.txt sample-right.txt

The command printed:

sample-left.txt sample-right.txt differ: byte 7, line 2
cmp reports the first differing byte and line

The report points to byte 7 on line 2, the first different position. Byte and line indices start at 1, so byte 7 is the seventh byte from the beginning. The line number gives text readers a place to inspect.

Only the first mismatch appears in the default report. That is enough to answer whether files differ, but it does not tell you how many later bytes also differ. Use -l for that more detailed inspection.

Step 2: List every differing byte

Add -l when the first difference is not enough. GNU cmp prints a decimal byte position followed by each file’s byte value in octal, which is useful for binary data or repeated differences.

cmp -l sample-left.txt sample-right.txt

For the two sample text files used above, the run produced these differing positions and octal values:

 7 142 102
 8 145 105
 9 164 124
10 141 101
cmp -l lists byte positions and octal values

Each position counts from the start of the files. The second and third columns show each operand’s byte value in octal. Octal is base eight, with digits from 0 through 7.

The position is the one-based byte offset. The octal values describe raw bytes, not characters decoded under a text encoding. A multibyte character can occupy several positions, and a value in the report may therefore identify one part of that character.

Use this mode when a compact inventory of mismatches helps narrow a binary inspection. It does not explain the meaning of those bytes. For structured formats, interpret the offsets with the format’s specification or a suitable viewer.

A long listing can be redirected to a file for later review. For automation, remember that a difference is a normal comparison result. A status above 1 signals that the comparison itself needs attention.

The GNU manual also documents a print-bytes mode for displaying the differing values.

Step 3: Check equality in a shell script

Use -s when a script needs to test equality without a difference message. See the LinuxForDevices guide to if/else in shell scripts for branching examples.

if cmp -s "$original" "$candidate"; then
    printf '%s\n' 'Files match'
else
    status=$?
    if [ "$status" -eq 1 ]; then
        printf '%s\n' 'Files differ'
    else
        printf '%s\n' 'cmp could not compare the files' >&2
        exit "$status"
    fi
fi

Save the script as cmp-script-demo.sh and run it with Bash:

bash cmp-script-demo.sh

On the sample files, the script prints:

Files differ
Shell script reports differing files using cmp status

The script saves cmp’s status before it prints the result, so the branch tests the comparison rather than printf. Quoting the variables protects filenames containing spaces and prevents shell word-splitting from turning one path into multiple operands.

For a production script, keep comparison errors separate from ordinary differences. A missing file means the requested comparison could not be completed, so the status branch preserves that distinction.

What cmp output and exit statuses mean

An exit status is the numeric result a shell receives after the command finishes. The shell stores it in the special variable $? until another command replaces it.

GNU cmp statusMeaningHow to handle it
0Inputs matchContinue with the equal-file path
1Inputs differReview or replace the candidate as appropriate
2Trouble prevented the comparisonCheck paths, permissions, and diagnostics

POSIX reserves values above 1 for errors, while GNU cmp uses 2. To support other implementations, treat any value above 1 as an error.

GNU cmp reports EOF when one file ends after matching the initial bytes of the other. It returns status 1 because the complete inputs differ.

For a missing path or unreadable input, check both operands and their access before interpreting a diagnostic as a content difference. The file command identifies the kind of data stored at a path and can help select a reader for an unknown format.

GNU cmp’s -n LIMIT compares no more than LIMIT bytes. Use it when the task concerns a prefix, but remember that matching bytes within that limit do not establish equality of the full files.

GNU’s extra options control how much of each input is compared or what a mismatch report contains. The option changes the comparison request, so choose it only when its effect matches the task.

GNU optionEffectUse it for
-bPrint differing bytesReadable byte values where possible
-i SKIPSkip initial bytesComparing data after a known header
-lList differing positions and octal valuesInspecting every mismatch
-n LIMITStop after LIMIT bytesChecking a deliberate prefix only
-sSuppress normal outputShell status checks

GNU cmp’s -i skips initial bytes. Its GNU form can skip a different number of bytes from each input, which helps when two binary structures have headers of different lengths. A skipped region is intentionally excluded, so equality after the skip does not prove that the complete files are identical.

When verifying a disk-image copy, the Linux guide to dd explains the copy workflow before cmp checks the result. GNU options may not exist on every Unix implementation, so consult cmp --help or man cmp for the installed command.

GNU cmp accepts a single hyphen as an input name for standard input. For example, this command compares generated text with a saved file:

printf '%s\n' 'alpha' | cmp - saved.txt

Bash process substitution provides temporary input paths, and it is available only in shells that implement that syntax. Use filenames or standard input when portability to other shells matters.

The Linux command line guide covers shell basics, and the diff tutorial explains readable line changes.

Common cmp edge cases

These cases can change what a comparison result means. Check the table before treating a quiet command or a matching prefix as proof that complete files are equal.

CaseWhat cmp doesWhat to do
One file ends firstReports EOF after the matching prefix and returns 1Check whether a shorter file is expected
One or both paths are missing or unreadableReports a diagnostic and returns an error statusVerify spelling, permissions, and that both inputs exist
Only a prefix is compared with -nStops at the requested byte limitDo not treat a prefix match as full-file equality
Initial bytes are skipped with -iCompares only the remaining portionsConfirm the skipped header is intentionally outside the check
Standard input is one operandReads that operand from the pipelineUse a single hyphen and ensure the producer supplies the intended bytes
Binary files have many mismatchesDefault mode stops at the first. The -l option may print many rowsUse -s for a yes/no test or redirect detailed output

Newline conventions are another common source of unexpected differences. A file ending in a newline has an extra byte compared with the same visible text without one. Likewise, a Windows-style carriage-return and line-feed ending differs byte-for-byte from a Unix line-feed ending.

When cmp reports different files but an editor displays the same words, inspect whitespace, line endings, and encoding bytes. For text-oriented context, use diff after locating the mismatch. For an exact integrity check, compare the complete files without -n or -i.

Options that narrow the comparison are useful for a deliberate task, such as checking a known data region. They are not a substitute for a full equality test. State the scope of the comparison in a script or note so another reader knows whether headers or trailing data were excluded.

Conclusion: Use cmp for byte-level checks

Choose cmp when the task calls for an exact comparison, then use the linked references to check GNU options or portable behavior.

For next steps, read the GNU cmp manual for GNU options and the POSIX cmp specification for portable behavior.

FAQ

These answers clarify what cmp checks and how to interpret its result.

What does cmp do in Linux?

cmp compares two files byte by byte and reports the first difference. It can also list differing bytes or return only an exit status.

What does cmp exit status 1 mean?

Status 1 means the inputs differ, including when one file ends after a matching prefix. GNU cmp uses status 0 for identical inputs and 2 for trouble.

When should I use cmp instead of diff?

Use cmp to check exact byte equality or locate differing bytes. Use diff when you need a line-oriented report of changes in text files.