Unix Shell Script Checking BST/GMT

A problem over the last weekend when the clocks went forward, showed there was a need to do resolve to how the GMT cron jobs should work on a few servers working together (when timing is important).

For a couple of years I simply changed the hour in the crontab on each server and left it at that, but alas this is open to error across multiple severs, so I decided to do something about it.

The first step was to put the cron table into GMT hours (i.e. ensure all jobs would run as GMT as normal). The next step was to introduce for the “morning run” of work, a check to sleep for an hour if the server is in British Summer Time (BST). We can find this out by using:

date

Which can give an output like this:

Mon Apr  1 12:17:55 BST 2013

All we want is the local time zone daylight savings flag and then do something if that is BST. We can get just this flag if we use the %Z parameter to the date command.

Here’s a little bit of code to wait if we’ve run in GMT but need to wait an hour due to BST:

# --- GMT checking - we assume run in GMT timeframe
SLEEPPERIOD=3600
GMTBST=`date '+%Z'`
if [ $GMTBST == BST ]
then
        # must be in summertime, so wait an hour
        echo "Found the date has $GMTBST. Sleeping for $SLEEPPERIOD seconds ..."
        sleep $SLEEPPERIOD
else
        echo "Not BST, carrying on"
fi

This is then done for the afternoon run and the same again for the evening run.

Note this may cause a problem if multiple scripts check this as they may get serial delays. This works best if you have one main job, and the check is done once.

So now the script will check if it is GMT or BST and wait an hour if BST.