As others have explained, using inotify
is the better solution. I'll just explain why your script fails. First of all, no matter what language you are programming in, whenever you try to debug something, the first rule is "print all the variables":
$ ls
file1 file2 file3
$ echo $PWD
/home/terdon/foo
$ for FILE in "${PWD}/*"; do echo "$FILE"; done
/home/terdon/foo/*
So, as you can see above, $FILE
is actually expanded to $PWD/*
. Therefore, the loop is only run once on the string /home/terdon/foo/*
and not on each of the files in the directory individually. Then, the md5sum
command becomes:
md5sum /home/terdon/foo/*
In other words, it runs md5sum
on all files in the target directory at once and not on each of them.
The problem is that you are quoting your glob expansion and that stops it from being expanded:
$ echo "*"
*
$ echo *
file1 file2 file3
While variables should almost always be quoted, globs shouldn't since that makes them into strings instead of globs.
What you meant to do is:
for FILE in "${PWD}"/*; do ...
However, there is no reason to use $PWD
here, it's not adding anything useful. The line above is equivalent to:
for FILE in *; do
Also, avoid using CAPITAL letters for shell variables. Those are used for the system-set environmental variables and it is better to keep your own variables in lower case.
With all this in mind, here's a working, improved version of your script:
#!/bin/bash
for file in *
do
sum1="$(md5sum "$file")"
sleep 2
sum2="$(md5sum "$file")"
if [ "$sum1" = "$sum2" ];
then
echo "Identical"
else
echo "Different"
fi
done
for FILE in "${PWD}"/*; do
works on the same set asfor FILE in *; do
it is not exactly equivalent because the latter one does not include the pathnames. – Lambert May 18 '16 at 10:40md5sum -- "$file"
instead ofmd5sum "$file"
to handle the case where a file begins with a-
. Of course you should also make your implementation of md5sum supports the--
end of options delimiter. – Harold Fischer Dec 28 '19 at 01:44