'Week of month' calculation for cron

Ryan Weal
Published 2006-07-10

For those of you who actually keep a regular schedule you will love this one. How often do you find that Unix is so much fun but it just can't do the simple math to figure out what week of the month it is? Well, with this script you will fix that in short order.

To accomplish this I owe one to Irek Szczesniak, who had created a script to put a calendar onto an image. Irek's code figured out what the week of the month was in some simple statements so I expanded upon these to produce some creative output.

Use 1: Finding the week of the month

This one is pretty simple, run the command and it will produce the current week of the month, assuming Monday as the first day and that the first "full week" is the one that counts.

kappa@verbosity.ca:~$ <b>wom</b><br /> 1<br /> <br /> kappa@verbosity.ca:~$

Here the script has checked the calendar and determined that the 9th of July in 2006 is the last day of the first full week. Again, rememeber that Monday is the first day of the week you crazy North Americans!

Use 2: Executing commands based on the week of month


This is what I really wrote the script for. The "wom" script also accepts one parameter which is the "desired week" you are seeking. If you input a value here it will be compared against the current week of the month and set the exit status accordingly.

kappa@verbosity.ca:~$ <b>wom 1 && date</b><br /> Sun Jul 9 21:06:42 PDT 2006<br /> <br /> kappa@verbosity.ca:~$ <b>wom 2 && date</b><br /> <br /> kappa@verbosity.ca:~$<br />

So, if you have a command that you want to put into your crontab all you need to do is prefix it with "wom 1 &&" to make sure it only happens on the first week of the month. Enjoy.



Thanks for Reading!
Ryan Weal (LinkedIn)
🍪 ☕
Send a comment 💬
Published by Kafei Interactive