Friday, 30 August 2013

Run a cron job on the last Saturday of the month, Linux

What:

Linux server - Debian, Ubuntu, Red Hat, SLES

Problem:

You need to run a bash script (backup) on the last Saturday of the month

Solution:

It might sound difficult, but it's not and there is more than one solution.

First solution, using a ncal:
#!/bin/bash

today=$(date +%d)
lastSat=$(ncal -h | awk '/Sa/{print $(NF)}')

if [ "$today" = "$lastSat" ]; then
    echo "Last Saturday of the month is today"
    exit 0
else
    echo "Not this time"
    exit 1
fi

In this solution we know straight away what's the last Saturday's date, so we just compare it with today's date.

Your cron job:
30 1 * * * /path/lastSatOfMonth && /path/my_script

Second solution is a bit more tricky, but works well too:
#!/bin/bash

today=`date +%a`
nextSat=`date +%d -d "+1 week"`
if [ "$nextSat" -lt 20 ] && [ "$today" = "Sat" ]; then
   echo "Last Saturday of the month is today"
fi

Important part is to set a cron job correctly, we can't use "day of month" and "day of week" in the same time as it would run cron job every Saturday and we need it to run only on Saturdays between 22nd and 31st of the month.

Your cron job:
30 1 22-31 * * /path/lastSatOfMonth

Bonus

How to run a backup on the last day of the month?
#!/bin/bash

today=`date +%d`
tomorrow=`date +%d -d "+1 day"`

if [ "$tomorrow" -lt "$today" ]; then
   exit 0
fi
exit 1
Your cron job:
30 1 * * * /path/lastDayOfMonth && /path/my_script

No comments:

Post a Comment