IF声明比较Unix中的两个文件

时间:2013-09-20 06:44:28

标签: unix if-statement scripting

我有一个unix脚本,它将为两个文件创建md5sum,然后检查这两个文件是否匹配。这是一个脚本的例子 - 但这不是正确地比较文件 - 任何人都可以对此有所了解吗?

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

3 个答案:

答案 0 :(得分:5)

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

如果已经计算了其中一个MD5校验和并将其存储在文本文件中,则可以使用

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

答案 1 :(得分:4)

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

可替换地:

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

答案 2 :(得分:-2)

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