Text and processing

The cmp command

Compares two files byte by byte and reports the first byte where they differ, with its line. With no output and exit code 0 the files are equal; with exit code 1 they differ.

Syntax

cmp [opciones] archivo1 archivo2Try it in the terminal →

Most useful options

-s, --quietPrints nothing; only sets the exit code. Ideal in scripts
-l, --verboseLists all differing bytes: position, value in the first file and value in the second, in octal
-b, --print-bytesAlso prints the differing bytes in readable form
-n, --bytes <n>Compares only the first n bytes
-i, --ignore-initial <n>Skips the first n bytes of both files before comparing

Copy-ready examples

$ cmp a.txt b.txttells you where the first difference is.

Example output

a.txt b.txt differ: char 7, line 2
$ cmp -s a.txt c.txt; echo $?checks silently whether they are equal. A 0 means they are.

Example output

0
$ cmp -l a.txt b.txtlists every differing byte. Here the s (163 in octal) in a.txt is a z (172) in b.txt.

Example output

7 163 172
$ cmp -n 1024 imagen.iso copia.isocompares only the start of the files, useful for a quick header check.

You can try them in the browser terminal: it does not touch your computer.

Common errors

MessageCauseFix
cmp: noexiste: No such file or directoryOne of the files does not exist or its name is misspelled.List the folder with ls and copy the exact name.
cmp: EOF on 'd.txt' after byte 7, in line 2One file ends before the other. Up to that byte they match, but the shorter one is cut off or truncated.Compare sizes with wc -c file, and copy the truncated file again.

Typical mistakes

  • cmp stops at the first difference. If you want all of them, use -l.

Differences from similar commands

  • diff: compares text files line by line and shows the changes. With binaries it only says they differ.
  • sha256sum: computes a fingerprint of each file. It helps compare with a published value or another machine, without having both files at hand.
  • md5sum: another fingerprint, now considered weak against collisions. It detects accidental changes, not attacks.

Security

cmp tells you whether two files are equal, but it authenticates nothing: whoever can change one can change the other too. To check a download, compare its sha256sum with the value the author published, and verify the signature if there is one.

Related commands

FAQ

Why does cmp say char and not letter?

Because it counts bytes, not characters. In UTF-8 a letter with an accent takes two bytes, so the number may not match what you see.

How do I compare two folders with cmp?

You cannot directly. Use diff -r for folders, or compare the sha256sum lists of both.

What exit code does it return?

0 if they are equal, 1 if they differ, and 2 if there is an error, such as a missing file.

More Text and processing commands

Learn to actually use it

The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.

Start the free course