Perhaps I am missing something, but I have a bash script that takes the output of ls, makes a hash, and then takes another one. If the hashes match, no action. If they are different, it should email an admin and then overwrite the hash so they match once again. Here is the script:
logday="$(date '+%Y-%m-%d')"
sdir="/home/admin/notify"
timestamp="$(date '+%Y-%m-%dT%H:%M:%S')"
log="$sdir/log/$logday-notification.log"
if ! test -f $sdir/hash1; then
touch $sdir/hash1
ls -alR /mnt/DVR/3 | md5sum > $sdir/hash1
else
echo "hash already present"
fi
ls -alR /mnt/DVR/3 | md5sum > $sdir/hash2
if cmp -s $sdir/hash1 $sdir/hash2; then
echo "$timestamp - Hash matches, nothing to do." >> "$log"
else
echo "$timestamp - Hash has changed! Sending notification. Writing new value to hash1" >> "$log"
cp -f $sdir/hash1 $sdir/hash2
echo "it changed" | mail -s "alert" email@gmail.com
fi
exit
So I run the script for the first time I get the log output of:
"Hash matches, nothing to do."
Makes sense. If I cat hash*, I get this
$ cat hash*
36d28cb4a6b384abe5c3acc81c93c891 -
36d28cb4a6b384abe5c3acc81c93c891 -
Again, makes sense
If I run it again, the hashes match, no email. Again, makes sense, nothing has changed yet.
Now, I make a change to the directory. I run the script. I get: " Hash has changed! Sending notification. Writing new value to hash1"
Yup makes sense, the hashes were different. The script overwrites the hashes so they should match now. Running cat hash* confirms this.
$ cat hash*
856d69a9b53008988d034c9504345541 -
856d69a9b53008988d034c9504345541 -
Both files are identical. But now, when I run the script again, it says they are still different!
I'm starting to run out of ideas why this happens. Any ideas?
logday="$(date '+%Y-%m-%d')" sdir="/home/admin/notify" timestamp="$(date '+%Y-%m-%dT%H:%M:%S')" log="$sdir/log/$logday-notification.log"
What you should do is quote your variables when you use them, socp "$sdir"
, etc. – muru Sep 09 '23 at 04:41cmp
? – ctrl-alt-delor Sep 09 '23 at 07:59cmp
to eliminate it from the problem. Remove the-s
, add-v
(verbose), and report its status (it could be 2 for "trouble"). If a bug is not staring you in the face, it (or they) are equally likely to be anywhere, and you might as well cram in debug everywhere as you write the code. – Paul_Pedant Sep 09 '23 at 10:53ls
by default shows the hours and minutes of times in the last 6 months, but instead the year of older ones. That will cause a change of output exactly 6 months after a file was last modified, even though the file's timestamp hasn't actually changed. (Depending on your platform, you may be able to work around that with--full-time
and/or--time-style
, but… (contd.) – gidds Sep 09 '23 at 19:10ls
's output, it's not good for other automated uses either.) – gidds Sep 09 '23 at 19:11touch
the file before you redirect output to it. – Barmar Sep 09 '23 at 19:53