Select Page

Backing up a complete WordPress site can be done with a bash script. This script has been created and described by Konstantin at http://theme.fm/2011/06/a-shell-script-for-a-complete-wordpress-backup-4/

Mobiledev.nl added some extra’s to the script.

Script features:

  • Backup all WordPress files in the WordPress dir
  • Backup the WordPress database
  • Compress these files into 1 backup file
  • Encrypt the backup file (mobiledev.nl addition)
  • Email the backup file as attachment (mobiledev addition)
  • Delete the non encrypted backup file (mobiledev addition)
  • Delete the encrypted file when it is 1 week old. (mobiledev addition)

Please read Konstantin’s explanation for a good understanding of the script.

The script:

#!/bin/bash
NOW=$(date +"%Y-%m-%d-%H%M")
FILE="site.$NOW.tar"
BACKUP_DIR="/home/yourname/backups"
WWW_DIR="/var/www/yoursite/"
DB_USER=""
DB_PASS=""
DB_NAME=""
DB_FILE="yoursite.$NOW.sql"
EMAIL="youremail"
ENCRYPTION_PASS="yourencryptionkey"
WWW_TRANSFORM='s,^var/www/yoursite,www,'
DB_TRANSFORM='s,^home/yourname/backups,database,'
tar -cvf $BACKUP_DIR/$FILE --transform $WWW_TRANSFORM $WWW_DIR
mysqldump -u$DB_USER -p$DB_PASS $DB_NAME > $BACKUP_DIR/$DB_FILE
tar --append --file=$BACKUP_DIR/$FILE --transform $DB_TRANSFORM $BACKUP_DIR/$DB_FILE
rm $BACKUP_DIR/$DB_FILE
gzip -9 $BACKUP_DIR/$FILE
openssl aes-256-cbc -salt -k $ENCRYPTION_PASS -in $BACKUP_DIR/$FILE.gz -out $BACKUP_DIR/$FILE.gz.enc
echo 'Backup attached' | mutt -s "Wordpress Backup" -a $BACKUP_DIR/$FILE.gz.enc -- $EMAIL
find $BACKUP_DIR -type f -mtime +7 -exec rm {} ;
find $BACKUP_DIR/*.gz -type f -exec rm {} ;

To be able to email from your server it might be necessary to:

  • raise the max email size (For example for Postfix set:  “Max size of message”)
  • install “mutt” to be able to send mail “apt-get install mutt”

This script can be used in a CRON job to do a scheduled backup. Unencrypted files will be deleted at the end of the script, encrypted files will be deleted after 7 days.

And you might want to decrypt…

openssl aes-256-cbc -d -in backupfile.tar.gz.enc -out site.tar.gz

This command will prompt for your encryption password. The result will be a compressed (tar.gz) file. If you unpack this file there will be a “www” and a “database” dir with the contents of your WordPress site.