There is the well-known diff command, but besides this there are at least two more ways to compare the contents of files.
First, here are three sample files to compare to:
# cat test1
1
2
3
4
5
6
# cat test2
1
b
c
4
5
6
# cat test3
1
2
3
4
5
6
#
The contents of test1 and test3 are the same, however test2 differs from these. Let’s see those comparisons!
# diff test1 test2
2,3c2,3
< 2
< 3
—
> b
> c
# diff test1 test3
#
Our first try is the diff command. As you can see, in the case of equality there is no output, and only the differring parts were displayed. Ok, but what about with all these strange outputs above? These are just plain commands for the good’ol ed tool, with these you could generate the file test2 from file test1. There is also a parameter to generate a scriptlet for ed, see the man 1 diff. If you don’t need the output and just wanted to check then redirect all from StdOut to /dev/null, and check the exit value. If it’s non-zero then the two are differing.
However there is another tool to check differences, with a little more user-friendlier output, it calls sdiff, this is aside-by-side difference program.
# sdiff test1 test2
1 1
2 | b
3 | c
4 4
5 5
6 6
# sdiff test1 test3
1 1
2 2
3 3
4 4
5 5
6 6
#
With sdiff everything will be displayed – the matching parts too – the first file on the left and the second file on the right side of your terminal. In case of a difference there will be a vertical line in the output. If you want to display only the distinct lines then you should pipe through a grep this, but bevare to escape the pipe character!
There is a third tool called cmp, specifically for scripts. It’s strengthness is its speed: it only checks if the two files are differing or not, and after the first difference it exits to terminal. It is very useful if you compare large files and are just curious if the files differ or not, and the differences doesn’t count.
# cmp test1 test2
test1 test2 differ: char 3, line 2
# cmp test1 test3
#
Just a note: there is a -h switch for diff, which is for fast checking, though it processes the whole file too. According to the man page: “Do a fast, half-hearted job. This option works only when changed stretches are short and well separated, but can be used on files of unlimited length.” For more info on the abovementioned commands see it’s corresponding man pages. And if you have another tool/method for comparing files, just leave a comment!