How to execute a cron on a specific day of the week once in the month?
This could look simple as we could think that this line in cron would do the trick:
# Run on every second Tuesday of the month 15 3 8-14 * 2 /usr/bin/bash /opt/myscriptfortuesday.sh
But this would not work as the ‘2’ for checking the Tuesday will come as a OR condition, and the command would be executed from day 8 to day 14 and on every Tuesday of the month.
As a workaround for that, you can use that command:
# Run on every second Tuesday of the month 15 3 8-14 * * test $(date +%u) -eq 2 && /usr/bin/bash /opt/myscriptfortuesday.sh
Here is the explanation of this cron line:
15 = 15th minute 3 = 3am 8-14 = between day 8 and day 14 (second week) * = every month * = every day of the week test $(date +%u) -eq 2 && /usr/bin/bash /opt/myscriptfortuesday.sh = the command to execute with a check on the date
Doing this check will allow to verify first that we are on the second tuesday before to execute the command. Don’t forget to add a backslash before the ‘%’ character to escape it.