Writing a bash loop to check differences in file size in loop

0

I am writing a continuous bash loop to check for new mail in the /var/spool/mail file. This script needs to be continuous and compares the size of the previous loop. If the size increases then it needs to echo something. This is what I have now. It is not echoing anything when I run it. I am not sure if it is picking up the difference in the size of the file. To run it you need to input ./"the name of the script" /var/spool/mail/user

#!/bin/bash
checkUsage()
{
while true
do
sleep 10
fileSize=$(stat -c%s $1)
        sleep 5;
        fileSizeNew=$(stat -c%s $1)

        if [ "$fileSize" -lt "$fileSizeNew" ]
        then
           echo -e  "[Notice : ] $USER you have mail!!!"
           exit 
        fi

done
}
checkUsage $1

guitar player

Posted 2017-07-25T22:23:59.707

Reputation: 1

Answers

0

Try this

#!/bin/bash
checkUsage()
{
fileSize=$(stat -c%s $1)
while true;     do
        sleep 10
        fileSizeNew=$(stat -c%s $1)
        if [ "$fileSize" -lt "$fileSizeNew" ]; then
                echo -e  "[Notice : ] $USER you have mail!!!"
           exit 
        fi

done
}
checkUsage $1

The problem with your current code is that you're only really checking for a difference in file size during the 5 seconds of the second sleep. Meaning that you'd re-declare fileSize every 10 seconds, then wait 5 seconds and re-declare fileSizeNew and compare them (Mind the 5 second gap).

In my example, you declare fileSize once because it's sitting outside of the while loop, so every 10 seconds we'll take a look at the new size and compare it to the old - ever lasting original file size.

Ulises André Fierro

Posted 2017-07-25T22:23:59.707

Reputation: 101

Thanks for the help. I came up with a new script. My problem with this is that after it echoes out the file size 2 times if nothing changed in /var/spool/mail/$USER it freezes. I need it to not do that and compare the size from old to new continuously. I do not know how to do that – guitar player – 2017-07-27T01:08:45.887

This is my new code. #!/bin/bash sleep 15; filename=/var/spool/mail/will filesize="$(du -b "$filename")" filesizeold="${filesize//[!0-9]/}" echo $filesizeold sleep 10; filename=/var/spool/mail/will filesize="$(du -b "$filename")" filesizenew="${filesize//[!0-9]/}" echo $filesizenew while true
do if [ $filesizeold -ne $filesizenew ]; then break fi done echo "$USER, You have
– guitar player – 2017-07-27T01:11:09.507

Adding the whole script to the comments isn't going to work. If this is a separate problem, please do go ahead and ask a new question, if it's the same one, just edit the original question to resemble whatever scenario you might've missed in the first place. – Ulises André Fierro – 2017-07-27T15:16:03.240