O'Reilly logo

Classic Shell Scripting by Nelson H. F. Beebe, Arnold Robbins

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Comparing Files

In this section, we look at four related topics that involve comparing files:

  • Checking whether two files are the same, and if not, finding how they differ

  • Applying the differences between two files to recover one from the other

  • Using checksums to find identical files

  • Using digital signatures for file verification

The cmp and diff Utilities

A problem that frequently arises in text processing is determining whether the contents of two or more files are the same, even if their names differ.

If you have just two candidates, then the file comparison utility, cmp, readily provides the answer:

$ cp /bin/ls /tmp                        
               Make a private copy of /bin/ls

$ cmp /bin/ls /tmp/ls                    
               Compare the original with the copy
                                         No output means that the files are identical
$ cmp /bin/cp /bin/ls                    
               Compare different files
/bin/cp /bin/ls differ: char 27, line 1  Output identifies the location of the first difference

cmp is silent when its two argument files are identical. If you are interested only in its exit status, you can suppress the warning message with the -s option:

$ cmp -s /bin/cp /bin/ls                 
               Compare different files silently

$ echo $?                                
               Display the exit code
1                                        Nonzero value means that the files differ

If you want to know the differences between two similar files, diff does the job:

$ echo Test 1 > test.1                   
               Create first test file

$ echo Test 2 > test.2                   
               Create second test file

$ diff test.[12]                         
               Compare the two files
1c1
< Test 1
---
> Test 2

It is conventional in using diff to supply the older file as the first argument. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required