知道两个二进制文件是否相同(除了时间戳)最简单的方法是什么(在Ubuntu Linux上使用图形工具或命令行)?我不需要提取差值。我只需要知道它们是否相同。


当前回答

使用sha1生成校验和:

sha1 [FILENAME1]
sha1 [FILENAME2]

其他回答

标准的unix diff将显示文件是否相同:

[me@host ~]$ diff 1.bin 2.bin
Binary files 1.bin and 2.bin differ

如果该命令没有输出,则意味着文件没有差异。

使用sha1生成校验和:

sha1 [FILENAME1]
sha1 [FILENAME2]

为了寻找闪存缺陷,我不得不写这个脚本,它显示所有包含差异的1K块(不仅仅是cmp -b所做的第一个)

#!/bin/sh

f1=testinput.dat
f2=testoutput.dat

size=$(stat -c%s $f1)
i=0
while [ $i -lt $size ]; do
  if ! r="`cmp -n 1024 -i $i -b $f1 $f2`"; then
    printf "%8x: %s\n" $i "$r"
  fi
  i=$(expr $i + 1024)
done

输出:

   2d400: testinput.dat testoutput.dat differ: byte 3, line 1 is 200 M-^@ 240 M- 
   2dc00: testinput.dat testoutput.dat differ: byte 8, line 1 is 327 M-W 127 W
   4d000: testinput.dat testoutput.dat differ: byte 37, line 1 is 270 M-8 260 M-0
   4d400: testinput.dat testoutput.dat differ: byte 19, line 1 is  46 &  44 $

免责声明:我在5分钟内破解了脚本。它不支持命令行参数,也不支持文件名中的空格

试试不同的

简单的回答:使用-s开关运行diff。

长话短说:继续往下读。


举个例子。让我们先创建两个包含随机二进制内容的文件:

$ 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

现在让我们复制第一个文件:

$ cp test1.bin copyoftest1.bin

现在test1.bin和test2.bin应该是不同的:

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

... test1.bin和copyoftest1.bin应该是相同的:

$ diff test1.bin copyoftest1.bin

但是等等!为什么没有输出?!?

答案是:这是有意为之。在相同的文件上没有输出。

但是有不同的错误代码:

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

$ echo $?
1


$ diff test1.bin copyoftest1.bin

$ echo $?
0

幸运的是,现在你不必每次都检查错误代码,因为你可以使用-s(或——report- identity -files)开关来让diff变得更详细:

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

使用cmp命令。如果它们是二进制相等,这将干净地退出,或者它将打印出第一个差值发生的位置并退出。