bashif-statementcomparisondouble-quotes

Why is this string comparation not working?


I'm trying to compare a md5 hash with one saved in a file, the result is that always the hashes are unqual, even when they are equal:

#!/bin/bash

checksum=$(ls <FOLDER> | md5sum)
last_checksum=$(cat CHECKSUM)

if [ "$checksum" != "$last_checksum" ]; then
    echo -n $checksum > CHECKSUM
    echo CHECKSUMS ARE UNEQUAL
fi

printing both checksums are equal.


Solution

  • It's because echo -n $checksum does not preserve the double space between the hash value and the filename, -, which means that if $checksum contains

    49a6b6e584f20a28509c1da3c311cda6  -
    

    Then what will be written to the file will instead be

    49a6b6e584f20a28509c1da3c311cda6 -
    

    Quotes will help to preseve the original string:

    echo -n "$checksum" > CHECKSUM
    

    You could also remove the filename part of the checksum since that's not interesting:

    checksum=$(ls . | md5sum | cut -d' ' -f1)