Wednesday, May 09, 2007

My backup scripts

I wanted to automate my backups of select files. I wanted my backup to do a monthly full backup, and a weekly incremential. I also wanted a rolling backup, so anything over the last 2 months would be overwritten or deleted.

Here is my monthly backup script, I saved as /etc/cron.monthly/monthly.bu:
#!/bin/sh
# Monthly backup script
# Makes a full backup

# Change the 2 variables below to fit your computer/backup
DIRECTORIES="/root /etc /var/log" # directories to backup
BACKUPDIR=/server/gonzobu # where to store the backups

# You should not have to change anything below here
MO=`date +%b` # Month name e.g. Apr
LOGFILE=$BACKUPDIR/$HOSTNAME.log # Log file
TIMEFILE=$BACKUPDIR/lastbackup # File to remember last backup

# Monthly full backup
tar --totals -cvf $BACKUPDIR/$HOSTNAME-$MO.tar $DIRECTORIES &> $LOGFILE

# Display settings for mailed in report by cron daemon.
echo Monthly full backup completed.
# Show stats and file names backed up, not top level directories
grep -v "not dumped" $LOGFILE | grep -v "/$"
# For stats only, comment line above, and uncomment line below
# grep "Total bytes" $LOGFILE

# Update lastbackup file
touch $TIMEFILE

# Clean up old backups (set to keep the last 2 months of backups)
find $BACKUPDIR -mtime +68 -delete


And here is my weekly backup I saved as /etc/cron.weekly/weekly.bu:
#!/bin/sh
# Weekly backup script
# Makes a incremental backup

# Change the 2 variables below to fit your computer/backup
DIRECTORIES="/root /etc /var/log" # directories to backup
BACKUPDIR=/server/gonzobu # where to store the backups

# You should not have to change anything below here
DM=`date +%d%b` # Date and Month e.g. 27Sep
LOGFILE=$BACKUPDIR/$HOSTNAME.log # Log file
TIMEFILE=$BACKUPDIR/lastbackup # File to remember last backup

# Check if first time run
if [ -f $TIMEFILE ]; then
NEWER="-N $TIMEFILE"
else
NEWER=""
fi

# Weekly incremental backup
tar $NEWER --totals -cvf $BACKUPDIR/$HOSTNAME-$DM.tar $DIRECTORIES &> $LOGFILE

# Display settings for mailed in report by cron daemon
echo Weekly incremental backup completed.
# Show stats and filesnames backed up, not top level directories
grep -v "not dumped" $LOGFILE | grep -v "/$"
# For stats only, comment line above and uncomment line below
# grep "Total bytes" $LOGFILE

# Update lastbackup file
touch $TIMEFILE


To make these work, first you need to create the backup directory in your file system. Then change the variables in each file to match your system (files to backup, and where to put the backups). Be sure to make both scripts executable. That's all there is to it.

To explain why I did the 68 days at the end of the monthly script, it's because I wanted to save a full 2 months. 31 days + 30 days + 1 full week (in case the week ends before the cron job runs).

No comments: