TonyW TonyW - 2 days ago 5
Linux Question

Bash MD5checksum loop

Each file has it's md5 checksum created, before my script looks at it, so these .md5 files already exist (They are made right after the files are tard). I'm checking to make sure nobody has changed any of the files, from the time they are created, to the time I look at it.

What i'm trying to do is loop through this list, find all .md5 checksums, and compare them with the md5 checksum of the actual file.

Example: This is what my directory looks like...

-rwxr-xr-x 1 awiles awiles 209904416 Nov 29 17:53 590465-1_v1.200.tar.gz*
-rwxr-xr-x 1 awiles awiles 57 Nov 29 17:53 590465-1_v1.200.tar.gz.md5*
-rwxr-xr-x 1 awiles awiles 1341076 Nov 29 17:53 590466-1_v1.320.tar.gz*
-rwxr-xr-x 1 awiles awiles 57 Nov 29 17:53 590466-1_v1.320.tar.gz.md5*
-rwxr-xr-x 1 awiles awiles 214723375 Nov 29 18:03 590467-1_v2.700.tar.gz*
-rwxr-xr-x 1 awiles awiles 57 Nov 29 18:03 590467-1_v2.700.tar.gz.md5*
-r-xr-xr-x 1 awiles awiles 2482573113 Nov 29 18:02 590468-1_v1.020.tar.gz*
-rwxr-xr-x 1 awiles awiles 46 Nov 29 18:02 590468-1_v1.020.tar.gz.md5*
-rwxr-xr-x 1 awiles awiles 28043339 Nov 29 17:53 590505-1_v1.040.tar.gz*
-rwxr-xr-x 1 awiles awiles 57 Nov 29 17:53 590505-1_v1.040.tar.gz.md5*


My current bash code...

for f in $DIR/*
do
if [[ $f == *".md5" ]] ; then
md5sum -c $f
fi
done


I'm getting the following errors...

md5sum: 590465-1_v1.200.tar.gz: No such file or directory
590465-1_v1.200.tar.gz: FAILED open or read
md5sum: WARNING: 1 listed file could not be read


What am I doing incorrectly here?

Answer

Judging by the output of md5sum, it expects 590465-1_v1.200.tar.gz to be in the current directory. Your script will only work when DIR is .. If that's not the case, then you should cd to $DIR first, for example like this:

(
cd "$DIR" && for f in *
do
  if [[ $f == *".md5" ]] ; then
      md5sum -c $f
  fi
done
)

I wrapped it in (...) so that you don't have to remember to cd "$OLDPWD" when you are done. (Using cd within scripts often leads to strange bugs due to oversight.)

Comments