Adsense 1

Sunday, June 01, 2008

how to run a cronjob on last Friday of every month

A crontab entry in linux looks like this:
10 10 * * 7 /path/to/your/script

This says to run /path/to/your/script at 10:10am on Sunday.

The first five fields are:
minute (0-59)
hour (0-23)
day of the month(1-31)
month of the year (1-12)
day of the week (0-7 with 0 &7 = Sunday, 1 = Monday etc.,)

For running a script on last Friday of every month you would typically put entry as:
10 10 28-31 * 5 /path/to/your/script

But the above will run your script on 28,29,30 & 31 of every month and on each Friday (weekly). The thing is, cron would execute the script if either day of the week or day of the month matches.

To run your script only on every last Friday/weekday of a month use the below entry:
10 10 * * 5 [ $(date +"\%m") -ne $(date -d 7days +"\%m") ] && /path/to/your/script

The above entry is executed every week. It has two parts:

First part:
$(date +"\%m") -ne $(date -d 7days +"\%m") - Checks if the month today is not equal to month next week (7days from now - same day). If they are equal then current
day (Friday in our case) is not the 'last Friday' if not it is the last

Second Part: your actual script /path/to/your/script

We have glued both parts with &&. This will effect the execution of second part ie., second part is executed only when the first part is true (Months returned from both date commands should not be equal).

Also note that there is a \ before %m in the entry. Cron cannot understand % sign and so we have to escape it with \.



  1. Hello, I want to run a Cron Job task on the last week day of the month. Any suggestions pls.


  2. Try mentioning specific dates (30,31) and combine with the above example. For months with 31 days the job will run twice though. May be try combining month & dates and see how it works.


  3. This will run your script at 10:10 on the last weekday of the month.

    10 10 26-31 * * date -d3day +\%d\%w | egrep -q "03[^23]|0[12]1" && /path/to/your/script

    Explained here:

  4. I've just made a standard solution for this. Anyone want to give it a try?

  5. Is there a way to check/verify this cron schedule with some input date? Or can the cron schedule can be verified only when it runs ?

    Any kind of verification will help, as I would not want it to not run at the expected time.