0

Basically, I have a series of commands I want to run every other sunday. I set a cron task to run the script every sunday, then this script only allows the script to run on even weeks, thus it only runs every other sunday. My question is, will this script still work going from year to year.

if [ $(($(date +'%U') % 2)) -eq 0 ]
then
  some command
fi
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
user2341453
  • 25
  • 1
  • 4
  • 4
    Have you tried testing it? You know you can change the clock on your computer to simulate this. – JohnFx May 02 '13 at 02:36
  • 1
    You don't have to change the clock. You can specify a date using `-d`. – paddy May 02 '13 at 02:38
  • You can write "every other week" in cron directly. See [a couple approaches here](http://stackoverflow.com/questions/350047/how-to-instruct-cron-to-execute-a-job-every-second-week) – Jeanne Boyarsky May 02 '13 at 02:45

2 Answers2

2

You have what's known as the XY problem here.

You have a problem with this part of your shell script, and you want to solve the problem by fixing the script. In reality, fixing the root cause of the problem is easier.

Simply alter your cron job to run every other Sunday:

#----+-----+-----+-----+-----+-------------------------------------------------
#min |hour |day  |month|day  |command
#    |     |of mn|     |of wk|
#----+-----+-----+-----+-----+-------------------------------------------------
03    04    *     *     7     expr `date +%W` % 2 >/dev/null || fortnightly.sh

See How to instruct cron to execute a job every second week? for more info.

Community
  • 1
  • 1
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
1

If you don't want to specify this with cron syntax, you can use the %s format instead of %U. This will give you the number of seconds since 1st Jan 1970 UTC. You can divide this to get a week number:

$(($(date +'%s') / 604800))

Then you can do your modulo test on that.

Note the number 604800 = 7 * 86400 = 7 * 24 * 60 * 60 ie the number of seconds in one week.

If you're running this every day, you'll want to know that it's actually a Sunday. So in this case, you would divide by 86400 to get a day number. Then, armed with the knowledge that day zero was a Thursday, you can check that the result (modulo 14) is either 3 or 10, depending on which Sunday you started at.

paddy
  • 60,864
  • 6
  • 61
  • 103