Jedv

Rsync backup script for websites (document root) & MySQL databases – to rsync.net or others

I have just got an account with rsync.net to backup one of my server’s websites, including the document root for the webserver and all the MySQL databases for them. I made a little more fancy Bash script for storing everything that is a little more complex than just one rsync command and caters for the dumping of the databases to individual named/dated files.

Read the header comments of the file for instructions on usage.

#!/bin/bash
# Backup a directory (document root) and all MySQL databases and send to rsync.net.
# You must have an account with rsync.net backup service (or similar) and have setup automatic ssh login via keys.
# See: http://www.rsync.net/resources/howto/ssh_keys.html
# Create the remote RSYNC_PATH using ssh before running the script.
# It is best to run this with a cronjob either daily/weekly/monthly,
# run it with --quiet in the crontab for no output except from errors
# <root@livingthedream.fun>

RSYNC_HOST=""
RSYNC_USER=""
RSYNC_PATH="" # Do not start or end the path with a /
MYSQL_USER=""
MYSQL_PASSWORD=""
DOCUMENT_ROOT_PATH="" # Do put trailing slash on this path.

# No need to edit below lines unless you need to modify behaviour.

databases=`mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES;" | tr -d "| " | grep -v Database`

QUIET=false
RSYNC_OPT="-avH"
if [ "$@" ] && [ "$@" == "--quiet" ]; then
 QUIET=true
 RSYNC_OPT="-avHq"
 echo "Starting backup.."
 echo "Dumping all MySQL databases.."
fi
mkdir -p sql
for db in $databases; do
    if [[ "$db" != "information_schema" ]] && [[ "$db" != "performance_schema" ]] && [[ "$db" != "mysql" ]] && [[ "$db" != _* ]] ; then
        if [ "$QUIET" = false ]; then
          echo "Dumping database: $db"
        fi
        mysqldump -u $MYSQL_USER -p$MYSQL_PASSWORD --databases $db > sql/`date +%Y%m%d`.$db.sql
    fi
done
if [ "$QUIET" = false ]; then
  echo "Done."
  echo "Sending SQL databases to $RSYNC_PATH/sql"
fi
rsync $RSYNC_OPT sql/ $RSYNC_USER@$RSYNC_HOST:$RSYNC_PATH/sql/
if [ "$QUIET" = false ]; then
  echo "Done."
  echo "Backing up document root to $RSYNC_PATH/sites"
fi
rsync $RSYNC_OPT $DOCUMENT_ROOT_PATH $RSYNC_USER@$RSYNC_HOST:$RSYNC_PATH/sites/
if [ "$QUIET" = false ]; then
  echo "Done."
  echo "All Done."
fi

Make sure to fill in the variables at the top and setup your cron job once you have tested it – checkout rsync.net for their awesome setup and nicely priced remote backup solutions. Their technical support is also most helpful.

 

Leave a Comment

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

*
*