Rudely copied from http://tldp.org/LDP/abs/html/filearchiv.html#FILECOMP

cmp

The cmp command is a simpler version of diff, above. Whereas diff reports the differences between two files, cmp merely shows at what point they differ.

Note

Like diff, cmp returns an exit status of 0 if the compared files are identical, and 1 if they differ. This permits use in a test construct within a shell script.

Example 15-33. Using cmp to compare two files within a script.

#!/bin/bash

ARGS=2 # Two args to script expected.
E_BADARGS=65
E_UNREADABLE=66

if [ $# -ne "$ARGS" ]
then
echo "Usage: `basename $0` file1 file2"
exit $E_BADARGS
fi

if [[ ! -r "$1" || ! -r "$2" ]]
then
echo "Both files to be compared must exist and be readable."
exit $E_UNREADABLE
fi

cmp $1 $2 &> /dev/null # /dev/null buries the output of the "cmp" command.
# cmp -s $1 $2 has same result ("-s" silent flag to "cmp")
# Thank you Anders Gustavsson for pointing this out.
#
# Also works with 'diff', i.e., diff $1 $2 &> /dev/null

if [ $? -eq 0 ] # Test exit status of "cmp" command.
then
echo "File \"$1\" is identical to file \"$2\"."
else
echo "File \"$1\" differs from file \"$2\"."
fi

exit 0

Tip: Use zcmp on gzipped files.

Advertisements