Awhile back, I had a user that wanted me to send out an email to all people in a distribution list on the last day of the month for them to put in some time reporting. After I spent some time tracking searching on the internet, I found a trick to get a task to work on the last day of the month with Cron. Below is what you need to make that happen.
First, you will need to create your script file using the below template:
#!/bin/bash TODAY=`date +%d` TOMORROW=`date +%d -d "1 day"` if [ $TOMORROW -lt $TODAY ]; then *COMMANDS/SCRIPT YOU WANT TO RUN* fi
Replace the *COMMAND/SCRIPT* line with whatever commands or scripts you want to run on the last day of the month. If you want it to run 2 days before the end of the month, change the 1 on line three to a 2.
Make sure the script is executable:
chmod u+x lastdayofmonth.sh
Then using crontab -e paste the following into a new line of your crontab to set the job to run at 6AM on the last day of the month every month.
0 6 28,29,30,31 * * /root/bin/lastdayofmonth.sh
Change the first two numbers to set up what minute and hour you want the script to run, and then change the path to point to where your script is located at.
Very interesting challenge, I never tried to implement a task to run the last day of the month and starting from your idea I think I found another way to do the same.
The idea is to run at 6 every day a cronjob which adds 1 day to the current date and extract just the 2 digits day of the altered date, then if it is equal to 01 we are on the last day of the month and we have to run our commandToRunLastDayOfTheMonth.sh:
0 6 * * * [ `date -d “1day” +%d` == 01 ] && commandToRunLastDayOfTheMonth.sh