0

I'm interested in writing a program that will get the size of the mail spool file for the user. (The spool files found in /var/spool/mail/$USER on Linux). To do this, I would like to create a continuous loop that excutes once every 30 seconds. Each time the loop executes, it will compare the size of the mail spool file with its size from the previous loop. If the new size is greater than the old size, I will have it print a message saying "You have new mail."

I've written the script below, but I'm failing to get it to work. Does anyone have any suggestions for me??

while true
do    
    clear    
    size= ls -l /var/spool | wc -c    
    sleep 30    
    newsize= ls -l /var/spool | wc -c    
    if [$size < $newsize]
    then    
            echo "You've got mail!"
    else    
            echo "Sorry no mail yet"    
    fi    
    sleep 30    
done &
muru
  • 193,181
  • 53
  • 473
  • 722
Justin
  • 2,071
  • 7
  • 26
  • 32
  • possible duplicate of [How to execute command every 10 seconds (without cron)?](http://askubuntu.com/questions/82616/how-to-execute-command-every-10-seconds-without-cron) – muru Nov 18 '14 at 15:06
  • Please code formatting by selecting the text and pressing Ctrl-K or clicking on the `<$>` icon. There are some spacing and syntax issues in your code. I am not sure whether that's from copying here or not. – muru Nov 19 '14 at 21:40
  • @muru, the code above is how I have it in the script. There are no errors from copying it here – Justin Nov 19 '14 at 21:45
  • 1
    In that case, have a look at a [syntactically correct version](https://gist.github.com/murukeshm/7d7f7bd4b6f3b53135bb). It might not be doing what you want, though. For example, I have no idea how a character count of the file listing of `/var/spool` will show a higher mail count, since `/var/spool` can also contain other things. – muru Nov 19 '14 at 21:51

2 Answers2

2

You can use an infinite loop in bash:

while true ; do
    # Your code here.
    sleep 30;
done

You can also schedule a periodic run of the checking program by cron.

choroba
  • 9,273
  • 1
  • 30
  • 42
2

Yes, you need an infinite loop with a sleep of 30 seconds. The following snippet will do:

#!/bin/bash
while true
do
    # do any stuff you want
    echo "doing my thing"
    # sleep for 30 seconds
    sleep 30
done

But I think that you will soon find that doing it in a bash script is probably not what you want to do. Tasks like this usually require some form of a daemon.

To answer your modified question, here is a variation of your script that should work as expected:

#!/bin/bash
while true
do
    clear
    size=$(ls -l /var/spool | wc -c)
    sleep 30
    newsize=$(ls -l /var/spool | wc -c)
    if [ $size -lt $newsize ]
    then
            echo "You've got mail!"
    else
            echo "Sorry no mail yet"
    fi
    sleep 30
done
BostonHiker
  • 627
  • 3
  • 7