How to compare two files byte by byte

Compare two files byte by byte using cmp file comparison utility.

Compare contents of the two files.

$ cmp fileA fileB
fileA fileB differ: char 590, line 12
$ cmp file1 file2
cmp: EOF on file1 after byte 950009856, in line 3903549

Compare the first 1 MiB.

$ cmp --bytes 1MiB fileA fileB
fileA fileB differ: char 590, line 12

Compare the last 1 MiB.

$ cmp --ignore-initial $(expr $(stat --format=%s file3) - $(expr 1024 \* 1024)) file3 file4
file3 file4 differ: char 1048574, line 17745

Supress output and use only exit code to indicate change.

$ LC_ALL=C cmp --silent fileA fileA
$ echo $?
$ LC_ALL=C cmp --silent fileA fileB
$ echo $?
$ LC_ALL=C cmp --silent file1 fileX
$ echo $?

exit code 0 will indicate that files are identical, exit code 1 that files are different and exit code 2 that there was some kind of error like inaccessible file.

Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.