How to Compare Two Files Byte-by-Byte Using the cmp Command in Linux

When you are debugging a corrupted software installation or trying to verify if two supposedly identical binary executables actually match, you cannot use standard text comparison tools like diff. Because compiled binaries contain unprintable machine code, attempting to run diff on them will either crash your terminal or output pages of absolute gibberish. To properly determine if two non-text files are identical, you must compare them at the raw binary level using the Linux cmp command.

How the cmp Command Works

The cmp (compare) utility performs a strict, byte-by-byte comparison of any two files. It does not care about lines, paragraphs, or formatting; it simply looks at the raw binary data. If the two files are 100% identical, the command will finish silently and return a zero exit code. If there is even a single bit of difference, it will report exactly where the deviation occurred.

To compare two executable files (e.g., the original program and a backup copy), simply run:

cmp original_binary backup_binary

If the files are different, the output will look something like this:

original_binary backup_binary differ: byte 4096, line 15

This tells you that the two files are perfectly identical up until the 4,096th byte, at which point the binary code diverges. (You can generally ignore the “line” number output when dealing with compiled binaries).

Listing All Byte Differences

By default, cmp stops processing the moment it finds the very first difference to save time. If you are actively patching a binary file and you want to see a comprehensive list of every single byte that differs between the two files, use the -l (verbose/list) flag.

cmp -l original_binary patched_binary

This command will output a three-column list. The first column is the byte number (the offset). The second column is the octal value of the byte in the first file, and the third column is the octal value of the byte in the second file. This is an incredibly powerful tool for reverse engineers and security researchers tracking exact hexadecimal modifications.

Using cmp in Bash Scripts

Because cmp is completely silent when files match, it is highly useful in bash scripts. You can use the -s (silent) flag to suppress all output entirely, even if the files differ, and rely solely on the exit code to drive your script logic.

if cmp -s fileA.tar.gz fileB.tar.gz; then
    echo "The archives are identical. No backup required."
else
    echo "The archives differ. Initiating backup sequence..."
fi

This ensures your automated scripts can reliably check for file integrity before overwriting critical backups.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.