brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: cmp compares two files byte by byte, and cmp -l lists every difference

Linux
~/tips/tip-shell-cmp-compare-files-byte-by-byte

cmp -l file1.bin file2.bin | head

Compares two files byte by byte and reports where they first differ, or all differing bytes with -l.

diff is for text. When the files are binary, such as a copied disk image or a download, I want a plain answer: are they the same or not?

cmp file1.bin file2.bin
cmp -l file1.bin file2.bin | head

Without options, cmp prints nothing when the files are identical. When they differ, it reports the byte and line number of the first difference and stops there. The exit status is 0 for identical files, 1 for different files and 2 if there was trouble, so it works nicely in a script with if cmp -s a b; then ..., where -s keeps it quiet.

-l (also called --verbose) goes through the whole file and prints the byte number of each difference, followed by the differing byte values. Byte numbers start at 1.

cmp -l file1.bin file2.bin | wc -l

That counts how many bytes differ, which is a quick way to see whether a copy is slightly damaged or completely different.

The caveat is the output format. According to the GNU manual, the byte numbers are decimal and the byte values are octal, which surprises people who expect hex. If one file is shorter, cmp also prints an end-of-file message. And on a huge pair of files with many differences, -l can produce an enormous amount of output, so pipe it through head or wc.

Further reading: GNU diffutils: options to cmp, cmp(1) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link