Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison function that compares two text files in Unix

Tags:

bash

unix

cmp

I was wondering if anyone could tell me if there is a function available in unix, bash that compares all of the lines of the files. If they are different it should output true/false, or -1,0,1. I know these cmp functions exist in other languages. I have been looking around the man pages but have been unsuccessful. If it is not available, could someone help me come up with an alternative solution?

Thanks

like image 560
Masterminder Avatar asked Oct 04 '12 21:10

Masterminder


1 Answers

There are several ways to do this:

  • cmp -s file1 file2: Look at the value of $?. Zero if both files match or non-zero otherwise.
  • diff file1 file2 > /dev/null: Some forms of the diff command can take a parameter that tells it not to output anything. However, most don't. After all, you use diff to see the differences between two files. Again, the exit code (you can check the value of $? will be 0 if the files match and non-zero otherwise.

You can use these command in a shell if statement:

if cmp -s file1 file2
then
   echo "The files match"
else
   echo "The files are different"
fi

The diff command is made specifically for text files. The cmp command should work with all binary files too.

like image 79
David W. Avatar answered Oct 22 '22 11:10

David W.