1

I'm trying to run a Bash script with Cron every 5 minutes to check if my Raspberry Pi have changed its IP address or not and update me, this is the script i'm using.

#!/bin/bash
#check and send ip address to email

MYIP=`ifconfig wlan0 | grep 'inet addr'| awk '{print $2}' | cut -d ':' -f 2`;
TIME=`date`;

LASTIPFILE='/var/www/crones/.last_ip_addr';
LASTIP=`cat ${LASTIPFILE}`;

if [[ ${MYIP} != ${LASTIP} ]]
then
#        echo "New IP = ${MYIP}"
#        echo "sending email.."
        echo -e "Hello\n\nTimestamp = ${TIME}\nIP = ${MYIP}\n\nBye" | \
                /usr/bin/mail -s "[INFO] New IP" dispositivos@cyclesmartcity.com;
        echo ${MYIP} > ${LASTIPFILE};
else
#        echo "no IP change!"
        echo ${MYIP} > ${LASTIPFILE};
fi

But i want this job to skip the first run when the device is initiated or rebooted since it is overlapping with another script that sends me the IP address at reboot.

I have tried multiple versions of the Cron code that i read online and they both do the job of running every 5 minutes but they keep running at minute 0 when my device is started or restarted.

5,10,15,20,25,30,35,40,45,50,55 * * * * root /bin/bash /var/www/crones/changeip.sh

or:

5-59/5 * * * * root /bin/bash /var/www/crones/changeip.sh

Is there a way in Cron that make the job skip the first reboot run ?? or if i need to modify the Bash script to add this condition, how to do it ?? Thank you!!

Salar Yunis
  • 45
  • 2
  • 9

2 Answers2

1

Two suggestions with regard to logic in the script:

1) Parse the output of uptime.

Or

2) Presuming /tmp is a tmpfs backed directory (meaning it disappears when the system shuts down and is created again at reboot; I believe this is the default with Raspbian but you can check this with mount | grep tmpfs, which if it doesn't show /tmp it will show you what directories you could use instead, e.g., /run).

tmpfile=/tmp/checksquiggle  # Arbitrary name
if [ ! -e $tmpfile ]; then
    touch $tmpfile &> /dev/null
    exit 0
fi

The only potential issue with this would be if the cron job runs before /tmp is available -- I would guess that is impossible, but if not it is probably very unlikely and at worst means you will skip ten minutes instead of 5.

Using the tmpfs backed file is more reliable than erasing it via a job at shutdown since the latter disappears no matter how the system stops (power fail, etc.) -- it only exists in RAM. It's also simpler.

goldilocks
  • 60,325
  • 17
  • 117
  • 234
0

There is no way to achieve what you want within cron.

man 5 crontab

You will have to add the appropriate logic to your script.

joan
  • 71,852
  • 5
  • 76
  • 108