19

I want to verify a file using md5sum -c file.md5. I can do that by hand, but I don't know how to check the validity in a script.

1 Answer 1

33

You can use md5sum's return status:

if md5sum -c file.md5; then
    # The MD5 sum matched
else
    # The MD5 sum didn't match
fi

To make things cleaner, you can add --status to tell md5sum (perhaps GNU's version only) to be silent:

if md5sum --status -c file.md5; then
    # The MD5 sum matched
else
    # The MD5 sum didn't match
fi

Shorter forms work just as well if appropriate:

md5sum --status -c file.md5 && echo OK
4
  • md5sum --status -c file.md5 && echo OK doesn't check for missing or extra files unfortunately May 2, 2017 at 7:40
  • 1
    @Erik what version of md5sum do you have? Regarding missing files, on the systems I’ve checked, md5sum --status -c file.md5 && echo OK does fail (and doesn’t print “OK”) if a file listed in file.md5 is missing. Regarding extra files, md5sum -c never complains about extra files, it only checks the files listed in the given checksum file. May 2, 2017 at 7:46
  • 1
    md5sum --status -c file.md5 && echo OK yields md5sum: stat 'foo': No such file or directory and OK on a mac May 2, 2017 at 9:41
  • You can put hashes in the script directly with something like echo 098f6bcd4621d373cade4e832627b4f6 test.txt | md5sum -c --status
    – mwfearnley
    Oct 18, 2022 at 12:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .