We want to extend our backup system to include a monthly end backup. It will be performed the last Sunday in the month but code below is so that I can see it works today on a smaller scale.
Started with (which works)
0 12 * * 0 sudo tar -cpzf /media/BackupDisk/wwwJUNEbackup.tar.gz /var/www
Have trawled the internet and come up with this code, tested in script file
if [ $(date +%d -d '+7 days') -le '8' ] ; then
echo "Yes"
else
echo "No"
fi
(For reference this says - if today's date + 7 days is less then or equal to 8 then YES else NO)
But when I try to include into the Sudo's crontrab
26 17 * 6 5 [ $(date +%d -d '+7 days') -lt '8' ] && sudo tar -cpzf /media/BackupDisk/wwwJUNEbackup.tar.gz /var/www
I get a nothing.
What am I doing wrong?
You use syntax far beyond basic shell => IMHO it is better to put it into a script with a specific shell, enforced via #!/...
.
Create a trivial script last_weekday_in_month.sh
:
#!/bin/bash
# Add one week to the current date and get its day-of-month
dom_a_week_from_today=`date +%d -d '+1 week'`
# trim any leading zero
dom_a_week_from_today=${dom_a_week_from_today#0}
# if next week is also next month, today's the last of this weekday for the month
[[ $dom_a_week_from_today -le 7 ]]
Use it in your crontab entry.
0 12 * * 0 /path/last_weekday_in_month.sh && sudo tar -cpzf /media/BackupDisk/wwwJUNEbackup.tar.gz /var/www