2

In Bash, how can I most easily check that the filename of a regular file is of the format shown below?

<filename>.<md5sum of file content>

For example, assume I had a file whose original name was foo.txt and had this content:

Hello world

The md5sum of this file is:

f0ef7081e1539ac00ef5b761b4fb01b3

Therefore, I have already changed the filename to:

foo.txt.f0ef7081e1539ac00ef5b761b4fb01b3

How, in Bash, may I best do the string processing necessary to verify that the portion of the filename after the last dot is indeed the md5sum of the file's content?

2 Answers 2

1

Considering a bash script where you give the filename you want to test as parameter :

./script.sh filename.f0ef7081e1539ac00ef5b761b4fb01b3

content of script.sh :

#!/bin/bash

#Get the md5 value from the filename (get the substring after the last '.' character)
expectedMD5=${1##*.}

#Calculate the md5sum value of the file
realMD5=$( md5sum $1 | awk '{ print $1 }' )

#Compare the 2 values
if [ $expectedMD5 = $realMD5 ]
then
        echo 'OK !'
else
        echo 'NOT OK'
fi
1

What @Félicien wrote is the gist of the answer. I just wanted to add that md5sum has a verification mode:

md5sum [OPTION]... [FILE]...

-c, --check
       read MD5 sums from the FILEs and check them

You could use it as follows. Assuming that f contains the file name, then

md5sum -c <( echo "${f##*.}" $f )

prints out

foo.txt.f0ef7081e1539ac00ef5b761b4fb01b3: OK

This uses a Bash trick known as process substitution. Essentially, the command first executes

echo "${f##*.}" $f

which prints out

f0ef7081e1539ac00ef5b761b4fb01b3 foo.txt.f0ef7081e1539ac00ef5b761b4fb01b3

But since md5sum -c takes it input from a file, rather than from standard input, the output of the echo needs to be directed into a temporary location in order for md5sum to ingest it, which is done with the <() construct.

You must log in to answer this question.

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