18

After downloading a file that has a md5 checksum available I currently check it with

md5 *file* | grep *given_checksum*

e.g.

md5 file.zip | grep -i B4460802B5853B7BB257FBF071EE4AE2

but it seemed funny to me to require grep and the pipe for what is surely a very common task. A stickler for doing things efficiently, I wondered there is a better way of doing this?

  • What kind of tool is that md5? From which package it comes? – manatwork Jun 05 '13 at 14:48
  • I didn't realise it was any different until I actually asked this question and started looking into the answers, but I'm using bash on OS X and it's Apple's own tool which doesn't have the -c option. Apparently they stopped bundling md5sum in 10.5... I've now installed the original unix md5sum tool. – Ben Griffiths Jun 05 '13 at 15:53

4 Answers4

30

md5sum has a -c option to check an existing set of sums, and its exit status indicates success/failure.

Example:

$ echo "ff9f75d4e7bda792fca1f30fc03a5303  package.deb" | md5sum -c -
package.deb: OK

Find a nice resource here

psusi
  • 17,303
  • 5
    Thanks. Just for completion, I now use md5sum -c - <<<"b4460802b5853b7bb257fbf071ee4ae2 file_name.ext" which seems cleaner than involving grep! – Ben Griffiths Jun 05 '13 at 15:56
  • hmm, not much improvement to the original $ md5 file | grep given_checksum and if you want to use case insensitive string you have to stick with grep -i – StandardNerd Oct 03 '17 at 11:50
  • 1
    I was getting no properly formatted MD5 checksum lines found when I was using md5sum -c <file.md5> <file> but this command worked for me. – Vishrant May 25 '19 at 17:24
  • I think this is easiest solution compare to writing if conditions in shell. It's good also it works also another sha functions like sha512sum – itirazimvar Nov 20 '22 at 11:15
4

The usual bash way would be:

shopt -s nocasematch
if [[ $(md5sum "$file") = 5d40f31729c992b5a0e67490689fe8ff* ]]
Hauke Laging
  • 90,279
1
md5sum -c <filename>.zip.md5 <filename>.zip

This will tell you Ok if they are the same.

This works with tar as well.

0

Inspired by psusi's answer

echo "$(cut -f1 -d' ' your_file.jar.md5) your_file.jar" | md5sum -c -

I used cut as not all the md5 are stored in the same way. Example

Vishrant
  • 121