Tag Archives: backup

Nightly backup your WordPress database and files

After rading Using a Cron job to keep things safe I didn’t found this really a complete procedure as it only backup the database… I think it’s better to backup everything at once and we usually have some associated files like for example themes, images uploaded, etc… remaining that we don’t won’t to lost. So here is a solution to keep a copy of everything no matter what happen and unobstructive while visitors are visiting.

UPDATE 03/02/2011 -1.1:

  • Added a functionality to remove all file into the backup folder older than the specified number of days. Just set days_delete and it will delete all files older than days_delete days.
  • Added security to stop script if an error goes wrong

Just set up a cronjob and you’re good to go.

#!/bin/sh
#
# Written by Emmanuel Pays 
#
# Description : Use this script to backup a WordPress blog
#
# wordpress_backup.sh ver. 1.1
#
# Latest version can be found at http://blog.loopion.com/

# Global config
set -e
www_path="/var/www/vhosts/"
backup_path_db="${www_path}backup_db/"
backup_path_files="${www_path}backup_files/"
domain="yourdomain.tld"
days_delete=5

#Production info
prod_uri="www.${domain}"
root_prod_path="${www_path}httpdocs/"
prod_db_name="name"
prod_db_username="username"
prod_db_pass="password"
#Create backup
backup_db_filename="database_$(date +%F_%Hh%M).bak.sql.bz2"
backup_file_filename="files_$(date +%F_%Hh%M).tar.bz2"

#Create files backups
tar -cjPf ${backup_path_files}prod_${backup_file_filename} ${root_prod_path}
chown ftproot:psaserv ${backup_path_files}prod_${backup_file_filename}
echo "Backup prod files done..."

mysqldump --add-drop-table -h localhost -u ${prod_db_username} -p${prod_db_pass} ${prod_db_name} | bzip2 -c > ${backup_path_db}${backup_db_filename}
chown ftproot:psaserv ${backup_path_db}${backup_db_filename}
echo "All backups done..."

#Delete older backups
find ${backup_path_db}* -mtime +${days_delete} -exec rm {} \;
echo "Deleted last ${days_delete} database backup"
find ${backup_path_files}* -mtime +${days_delete} -exec rm {} \;
echo "Deleted last ${days_delete} files backup"

Coming soon a deployment script…