Search code examples
bashubuntuchecksum

checksum bash script in ubuntu


I have two folders with same file names inside. How can I do a checksum in bash to evaluate which files are different or identical? Currently, I've written a bash script below which builds corresponding file names and does "cksum" on them, which generates two numbers per checksum. But I have to somehow save these two numbers for each record and subtract them to see which one's a non-match.

#!/bin/bash
folderOld="home/OldFiles/"
folderNew="home/NewFiles/"
for ((fileNumber=1;fileNumber<1000000;fileNumber++))
do
FileName="file${fileNumber}.dat"
OldFile=$folderOld$FileName
NewFile=$folderNew$FileName
cksum $OldFile
cksum $NewFile
done

Solution

  • You don't need to subtract the numbers, you just need to check whether they are equal:

    OldSum=$(cksum $OldFile | cut -d' ' -f1)
    NewSum=$(cksum $NewFile | cut -d' ' -f1)
    if [[ $OldSum != $NewSum ]]; then
        # Checksum mismatch, do something useful here
    fi
    

    I'm using cut -d' ' -f1 here to split the line on spaces, and take the first field. So file size and file name are ignored.

    By the way, cksum uses CRC32 by default, which has a fair risk of false negatives on so many files. Better to use, for example, sha256sum.