Using date and cron to Run a Script on the Nth Day

Problem

You need to run a script on the Nth weekday of the month (e.g., the second Wednesday), and most crons will not allow that.

Solution

Use a bit of shell code in the command to be run. In your Linux Vixie Cron crontab adapt one of the following lines. If you are using another cron program, you may need to convert the day of the week names to numbers according to the schedule your cron uses (0–6 or 1–7) and use +%w (day of week as number) in place of +%a (locale’s abbreviated weekday name):

# Vixie Cron
# Min Hour DoM Mnth DoW Program
# 0-59 0-23 1-31 1-12 0-7

# Vixie Cron requires % to be escaped or you get an error!

# Run the first Wednesday @ 23:00
00 23 1-7 * Wed [ "$(date '+\%a')" == "Wed" ] && /path/to/command args to command

# Run the second Thursday @ 23:00
00 23 8-14 * Thu [ "$(date '+\%a')" == "Thu" ] && /path/to/command

# Run the third Friday @ 23:00
00 23 15-21 * Fri [ "$(date '+\%a')" == "Fri" ] && /path/to/command

# Run the fourth Saturday @ 23:00
00 23 22-27 * Sat [ "$(date '+\%a')" == "Sat" ] && /path/to/command

# Run the fifth Sunday @ 23:00
00 23 28-31 * Sun [ "$(date '+\%a')" == "Sun" ] && /path/to/command

Warning

Note that any given day of the week doesn’t always happen five times during one month, so be sure you really know what you are asking for if you schedule something for the fifth week of the month.

Warning

Note that Vixie Cron requires % to be escaped or you get an error like /bin/sh: 1: Syntax error: EOF ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.