3

I have a shell script that runs via crontab, but the commands in it are timezone dependent (they refresh a table in database everyday. If the script runs during the time of a DST change, it will replicate inconsistent period of data.

I am planning to use a wrapper script that:

  1. Checks if timezone between today and tomorrow is different
  2. runs the child script only if first check returns false (its not different)

There's plenty of informatin on changing the timezone, but nothing on checking if the timezone changed in linux/bash.

2
  • 2
    Personally, I'm surprised that you do not record the GMT time in the database and then convert it back to localtime when needed. Thus there would be no issue here. Commented Nov 18, 2014 at 22:00
  • What time of day does this cron job run? Commented Nov 18, 2014 at 22:02

2 Answers 2

3

The following tests whether the local timezone has changed since yesterday:

[ "$(date -d "yesterday" '+%z')" = "$(date '+%z')" ] 

The %z format asks date to return the timezone. The above compares the result for today versus the result for yesterday.

How to use it

The test command can be used to control statement execution:

$ [ "$(date -d "yesterday" '+%z')" = "$(date '+%z')" ] && echo "No change" No change 

Or,

$ if [ "$(date -d "yesterday" '+%z')" = "$(date '+%z')" ]; then echo "No change"; fi No change 

How it works

The output from the %z format looks like:

$ date '+%z' -0800 $ date -d yesterday '+%z' -0800 

The above indicates an 8 hour lag behind GMT. That lag depends on whether we are in daylight savings or standard time. For example:

$ date -d "nov 1, 2014" '+%z' -0700 

[ indicates bash's text command. The following command compares the results of today versus yesterday:

[ "$(date -d "yesterday" '+%z')" = "$(date '+%z')" ] 
0

Just a point of clarification: date -d yesterday +%z will tell you whether yesterday would have reported a different time-of-day for the same time that today would, assuming the system was set to the same timezone yesterday. It won't tell you whether someone may have replaced /etc/localtime with a different default system-wide timezone.

Strictly speaking, daylight savings isn't a change of timezone, it's just a change of your timezone's offset from UTC. It's still the same timezone.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.