Dustin Cook
Dustin Cook

Reputation: 1305

IF Statement to Compare Two Files in Unix

I have a unix script, that will create the md5sum for two files and then check that the two files match. This is an example of the script - but this is not comparing the files correctly - can anyone shed some light on this?

md5sum version1.txt >> file1
md5sum version2.txt >> file2

if [ $file1 == $file2 ]
then
    echo "Files have the same content"
else
    echo "Files have NOT the same content"
fi

Upvotes: 1

Views: 6733

Answers (3)

jlliagre
jlliagre

Reputation: 30823

if [ "$(md5sum < version1.txt)" = "$(md5sum < version2.txt)" ]; then
    echo "Files have the same content"
else
    echo "Files have NOT the same content"
fi

If one of the MD5 checksums is already computed and stored in a text file, you can use

if [ "$(md5sum < version1.txt)" = "$(awk '{print $1}' md5hash.txt)" ]; then
...

Upvotes: 5

clstrfsck
clstrfsck

Reputation: 14829

HASH1=`md5sum version1.txt | cut -f1 -d ' '`
HASH2=`md5sum version2.txt | cut -f1 -d ' '`

if [ "$HASH1" = "$HASH2" ]; then
    echo "Files have the same content"
else
    echo "Files have NOT the same content"
fi

Alternatively:

if cmp -s version1.txt version2.txt; then
    echo "Files have the same content"
else
    echo "Files have NOT the same content"
fi

Upvotes: 4

Abdul Hamid
Abdul Hamid

Reputation: 3252

if [ "$file1" == "$file2" ]
then
    echo "Files have the same content"
else
    echo "Files have NOT the same content"
fi

Upvotes: -2

Related Questions