4

hi I want to create a bash file on linux, which checks the md5 hash of a file against a backup md5 hash, so i know if the original file has been tampered with. The script should output the md5 hash of two files and than compare the two created hash files:

md5sum file1 > file1.md5 | cut -c -32
if [ file1.md5 =! backup.md5 ] then;
   #send email

but it does not work, there is still the filename in the file.md5, has someone an idea on how to only get the has to the file.md5?

MadMax
  • 143
  • 4
  • 14

4 Answers4

6

There are several issues with your script.

First you apply cut -c -32 after you have redirected the md5sum output to file1.md5 already, which is why it does nothing.

You should restructure it like that, instead:

md5sum file1 | cut -c -32 > file1.md5

Next, you can not really compare files with =! directly, you have to read and compare their content instead, like this:

[ "$(cat file1.backup.md5)" != "$(cat file1.real.md5)" ]

Also note that md5sum does already have a "check mode", so you can simply do this:

#Save MD5 sum of your file to backup.md5, in md5sum native format
md5sum file1 > backup.md5

#Later on ...
if ! md5sum -c backup.md5; then
...
zeppelin
  • 8,947
  • 2
  • 24
  • 30
  • thanks, the check mode didn't work, because i always copy the file to a different location before creating the md5 hash, so i can be sure, that it is not encrypted – MadMax Apr 28 '17 at 11:49
1

You have the wrong order of the commands. Write the

md5sum file1 | cut -c -32 > file1.md5
TMS
  • 749
  • 7
  • 14
1

Re: "there is still the filename in the md5 [string], ... how to only get the hash?"

The string that md5sum returns is (or at least is structured like) a record with two fields or a tuple with two elements. E.g.,

$ md5sum filename.txt 8d7dd71ff51614e69339b03bd1cb86ac filename.txt

To grab only the hash (the first field/element), try piping the string to awk like so:

$ md5sum filename.txt | awk '{print $1}' 8d7dd71ff51614e69339b03bd1cb86ac

I submit this answer to this specific part of OP's question asked over a year ago for others who are working on similar issues and stumble upon this thread as I did.

Karl Baker
  • 903
  • 12
  • 27
0

Pipe is in wrong position.Use like this:

 md5sum file1| cut -c -32 > file1.md5

Or for full implementation without saving md5 sums to files:

ORG_SUM=`md5sum org_file | cut -c -32`
BCK_SUM=`md5sum bck_file | cut -c -32`
if [ "${ORG_SUM}" != "${BCK_SUM}" ]; then
   #send email
fi
derkan
  • 475
  • 4
  • 5