How to compare binary files to check if they are the same?

前端 未结 14 711
傲寒
傲寒 2020-12-07 09:25

What is the easiest way (using a graphical tool or command line on Ubuntu Linux) to know if two binary files are the same or not (except for the time stamps)? I do not need

14条回答
  •  一个人的身影
    2020-12-07 10:04

    Try diff -s

    Short answer: run diff with the -s switch.

    Long answer: read on below.


    Here's an example. Let's start by creating two files with random binary contents:

    $ dd if=/dev/random bs=1k count=1 of=test1.bin
    1+0 records in
    1+0 records out
    1024 bytes (1,0 kB, 1,0 KiB) copied, 0,0100332 s, 102 kB/s
    
                                                                                      
    $ dd if=/dev/random bs=1k count=1 of=test2.bin
    1+0 records in
    1+0 records out
    1024 bytes (1,0 kB, 1,0 KiB) copied, 0,0102889 s, 99,5 kB/s
    

    Now let's make a copy of the first file:

    $ cp test1.bin copyoftest1.bin
    

    Now test1.bin and test2.bin should be different:

    $ diff test1.bin test2.bin
    Binary files test1.bin and test2.bin differ
    

    ... and test1.bin and copyoftest1.bin should be identical:

    $ diff test1.bin copyoftest1.bin
    

    But wait! Why is there no output?!?

    The answer is: this is by design. There is no output on identical files.

    But there are different error codes:

    $ diff test1.bin test2.bin
    Binary files test1.bin and test2.bin differ
    
    $ echo $?
    1
    
    
    $ diff test1.bin copyoftest1.bin
    
    $ echo $?
    0
    

    Now fortunately you don't have to check error codes each and every time because you can just use the -s (or --report-identical-files) switch to make diff be more verbose:

    $ diff -s test1.bin copyoftest1.bin
    Files test1.bin and copyoftest1.bin are identical
    

提交回复
热议问题