Date created: Sunday, June 19, 2011 12:04:27 PM. Last modified: Sunday, January 27, 2019 11:46:10 AM
Monthly Rsync Backup Example
A monthly rsync backup from a remote server into a folder for the current month of the year. Each time it runs it will check if there is a folder for last month and copy that folder contents in a folder for this month before running rsync. Rsync now already has most of the files it needs to so it would save time and bandwidth by just synchronising the changes (this can be improved with soft/hard links but if space is not a premium this method provides more copies of the data);
#!/bin/bash backupDir="/backup/remoteserver" lastMonth=`date --date="$(date +%Y-%m-15)-1 month" +%Y-%m` # Make sure this month's backup directory exists if [ ! -d $backupDir/`date +%Y-%m` ]; then mkdir $backupDir/`date +%Y-%m` echo "created $backupDir/`date +%Y-%m`" fi # Check if there is a backup directory for last month and if there is, # copy that across to be a base for the rsync to save bandwidth and time if [ -d $backupDir/$lastMonth ]; then echo "found: $backupDir/$lastMonth" cp -R $backupDir/$lastMonth/* $backupDir/`date +%Y-%m`/ echo "copied $backupDir/$lastMonth" fi echo "syncing..." rsync -azv -e 'ssh' --delete-during --ignore-errors user@remotebox:/dir/to/backup $backupDir/`date +%Y-%m`/
When getting last month from the 'date' command we get the date one month ago from the current month if it were the 15th. If for example you ran the script on the 1st of March the 'date' command would get the month 30 days ago and if last month was say February, it would return Janurary.
Taken from 'info date' section '28.6 Relative items in date strings';
The fuzz in units can cause problems with relative items. For example, `2003-07-31 -1 month' might evaluate to 2003-07-01, because 2003-06-31 is an invalid date. To determine the previous month more reliably, you can ask for the month before the 15th of the current month. For example: $ date -R Thu, 31 Jul 2003 13:02:39 -0700 $ date --date='-1 month' +'Last month was %B?' Last month was July? $ date --date="$(date +%Y-%m-15) -1 month" +'Last month was %B!' Last month was June!
Previous page: Eve Config Bacup
Next page: Rsync Backup Window