I need a function to compare 2 binary files, here the requirements:
- 2 files, not 3 or 4
- files can't be assumed to exist
- avoid running checksum (CRC/MD5/SHA/...) until one must
- if running multiple checksums, do so from least expensive to most expensive (order above)
- print out meaningful error messages
- usage: binary_compare_two_files file1 file2
Here's what I have got, I think it can be done much better than this. How?
#!/bin/bash
function binary_compare_two_files() {
REQUIRED_ARGUMENTS=2
n_arguments="$#"
if [ ! "${n_arguments}" -eq $REQUIRED_ARGUMENTS ]; then
printf 'Invalid number of arguments. Required: %d, supplied: %d\n' \
$REQUIRED_ARGUMENTS $n_arguments
echo 'usage: binary_compare_two_files file1 file2'
return
fi
file1="${1}"
file2="${2}"
if [ ! -f "${file1}" -o ! -f "${file2}" ]; then
echo 'Invalid arguments. Both arguments need to refer to existing files.'
return
fi
file1_size=$(stat -f "%z" "${file1}")
file2_size=$(stat -f "%z" "${file2}")
if [ ! ${file1_size} -eq ${file2_size} ]; then
return $((file1_size - file2_size))
fi
file1_md5=$(md5 -q "${file1}")
file2_md5=$(md5 -q "${file2}")
if [ ! "${file1_md5}" == "${file2_md5}" ]; then
return -1
fi
return 0
}
I have opted not to use diff/bdiff because I am not sure whether those stat and check for sizes first... I would need to look at the src.
cmpordiff? – enzotib Sep 2 '12 at 10:12statfirst seems instantaneous rather than "line by line". – Robottinosino Sep 2 '12 at 10:23diffand see what that does... – Robottinosino Sep 2 '12 at 10:26cmp? – Mat Sep 2 '12 at 11:26diffworks for binary files:diff a bgivesBinary files a and b differ.cmpmay well be better. You definitely don't need a script for this. – terdon Sep 2 '12 at 11:44