WordPress Backup Script

My WordPress backup script, which keeps daily, weekly and monthly backups of website files and database dumps.

Installation:

This should work on your garden variety Debian or Ubuntu server running WordPress and Mysql.

Copy this script to /usr/local/sbin/backup-websites

cat /etc/cron.d/backup-websites
# Backup websites and databases at around 3am
15 03 * * * root /usr/local/sbin/backup-websites

btw. sorry the indentation seems to go missing when I use the /code tag in WordPress.

Obligatory Muppets Photo

The script…

backup-websites:


#!/bin/bash
# Backup websites and databases

####
# Set some variables and paths

BACKUP_DIR=home/backups/websites
# Must contain backup.monthly backup.weekly backup.daily folders

FILE_DIRS_BASE=var/www
DATABASES=`echo "show databases" | /usr/bin/mysql --defaults-file=/etc/mysql/debian.cnf | grep -v Database | grep -v schema`

email=root@localhost

######
# Make appropriate destination directory

# Destination file names
date_daily=`date +"%Y-%m-%d"`

# Get current month and week day number
month_day=`date +"%d"`
week_day=`date +"%u"`

# On first month day do monthly
if [ "$month_day" -eq 1 ] ; then
destination=backup.monthly/$date_daily
else
# On Saturdays do weekly
if [ "$week_day" -eq 6 ] ; then
destination=backup.weekly/$date_daily
else
# On any regular day do daily
destination=backup.daily/$date_daily
fi
fi

cd /$BACKUP_DIR
mkdir $destination

# latest backup symlink
ln -snf $destination /$BACKUP_DIR/latest

####
# Create backup files in today's directory

stamp=`date +%Y-%m-%d_%H-%M-%S`

# Dump MySQL tables in incoming dir
for db in $DATABASES; do
/usr/bin/mysqldump --defaults-file=/etc/mysql/debian.cnf $db | bzip2 > \
/$BACKUP_DIR/$destination/$db.$stamp.sql.bz2
done

FILE_DIRS=`ls /$FILE_DIRS_BASE`

# Compress files, one tar file per sub directory
for filedir in $FILE_DIRS; do
tar -C / -cjf /$BACKUP_DIR/$destination/$filedir.$stamp.tar.bz2 $FILE_DIRS_BASE/$filedir
done

#####
# Email backup info

ls -l /$BACKUP_DIR/$destination/ | mail -s "[`uname -n`] Websites Backup $date_daily" $email

#####
# Clean up old backups

# Daily - keep for 7 days
find /$BACKUP_DIR/backup.daily/ -maxdepth 1 -mtime +7 -type d -exec rm -rf {} \;

# Weekly - keep for 30 days
find /$BACKUP_DIR/backup.weekly/ -maxdepth 1 -mtime +30 -type d -exec rm -rf {} \;

# Monthly - keep for 365 days
find /$BACKUP_DIR/backup.monthly/ -maxdepth 1 -mtime +365 -type d -exec rm -rf {} \;

#END

Keep your backups for less time by updating mtime above.

To recover your backups:

tar jxvf your-backup-file.tar.bz2
bunzip2 your-backup-file.sql.bz2

LLAP.

Leave a Reply

Your email address will not be published. Required fields are marked *