How do I compare two files with a shell script?
diff
sets its exit status to indicate if the files are the same or not. The exit status is accessible in the special variable $?
. You can expand on Ignacio's answer this way:
diff --brief <(sort file1) <(sort file2) >/dev/null
comp_value=$?
if [ $comp_value -eq 1 ]
then
echo "do something because they're different"
else
echo "do something because they're identical"
fi
In bash:
diff --brief <(sort file1) <(sort file2)
Whilst diff
is a perfectly fine answer, I'd probably use cmp
instead which is specifically for doing a byte by byte comparison of two files.
https://linux.die.net/man/1/cmp
Because of this, it has the added bonus of being able to compare binary files.
if cmp -s "file1" "file2"
then
echo "The files match"
else
echo "The files are different"
fi
I'm led to believe it's faster than using diff
although I've not personally tested that.