(Automated) Manual Backup of a Drupal 7 Website (Including the Database)

Did you ever want to create a backup of both, your drupal 7 installation files and the associated mysql database? Here is how you can do it with almost no configuration.

#!/bin/sh

#############################################################################
#                                                                           #
#                           Drupal 7 Backup                                 #
#    Run this script on the server containing your Drupal 7 installation.   #
# TODO: Does not use the table prefix yet / backs up the complete database. #
# Inspired by <https://gist.github.com/737577>                              #
#                                                                           #
#############################################################################

#################
# RESTORE INFO: #
#################
# * Move the .tar file to your drupal dir and run `tar -xf file-timestamp.tar`
# * Restore database: `gunzip -c site-timestamp.sql.gz | mysql dbname -u dbuser -p`


###############################################
# CHANGE THESE OPTIONS TO MATCH YOUR SYSTEM ! #
###############################################

sitedir=/var/www/mydrupalsite/ # the directory Drupal is installed in
backupdir=~/files/mydrupalsite_backup # the directory to write the backup to
configfile=$sitedir/sites/default/settings.php

##################
# END OF OPTIONS #
##################

test ! -d $backupdir && mkdir $backupdir
siteDBserver=`grep -v "^[[:space:]]\*" $configfile | grep -A 6 "'database'" | grep "'host'" | cut --delimiter=">" -f2 | cut --delimiter="'" -f2`
siteDBname=`grep -v "^[[:space:]]\*" $configfile | grep -A 6 "'database'" | grep "'database'" | cut --delimiter=">" -f2 | cut --delimiter="'" -f2`
siteDBuser=`grep -v "^[[:space:]]\*" $configfile | grep -A 6 "'database'" | grep "'username'" | cut --delimiter=">" -f2 | cut --delimiter="'" -f2`
siteDBpassword=`grep -v "^[[:space:]]\*" $configfile | grep -A 6 "'database'" | grep "'password'" | cut --delimiter=">" -f2 | cut --delimiter="'" -f2`
siteDBprefix=`grep -v "^[[:space:]]\*" $configfile | grep -A 6 "'database'" | grep "'prefix'" | cut --delimiter=">" -f2 | cut --delimiter="'" -f2`
sitedb=$siteDBname
mysqlopt="--host=$siteDBserver --user=$siteDBuser --password=$siteDBpassword --skip-lock-tables"

timestamp=`date +%Y-%m-%d`

dbdump="$backupdir/site-$timestamp.sql.gz"
filedump="$backupdir/site-$timestamp.files.tgz"

echo "Drupal backup. Database: $sitedb; Directory: $sitedir; Backup to: $backupdir"
echo
echo "Creating database dump $dbdump..."
mysqldump --default-character-set=utf8 $mysqlopt "$sitedb" | gzip > "$dbdump" || exit $?

echo
echo "Creating file archive $filedump..."
cd "$sitedir"
tar -zcf "$filedump" . || exit $?

echo
echo "Done!"
echo "Files to copy to a safe place: $dbdump and $filedump"

#######
# END #
#######

Comments