Site backup script example

This handy script will backup a directory and database. To use, create a new file on your server, probably in your user’s root, called backup.sh and add the below, making sure to update the source and destination path varaibles and database name.


#!/bin/bash 

echo "Please enter backup name: "
read SITENAME
TIME=`date +%F-%H%M%S`                   # time stamp to the backup file
FILENAME=$SITENAME"_"$TIME".tar.gz"      # site backup filename
DB_FILENAME=$SITENAME"_"$TIME".sql.gz"   # db backup filename
DB_NAME="qwewprxqtr"
DB_USER="qwewprxqtr"

SRCDIR="/var/www/public_html"     # directory to back up
DESDIR="~/_backups"               # directory to save backup to

## do the db backup
mysqldump --user=$DB_USER -p --default-character-set=utf8 $DB_NAME | gzip > "$DESDIR/$DB_FILENAME"

echo "mysqldump finished: $DB_FILENAME"

## do the tarring, with a sample --exclude flag for 
## the option to exclude a folder

tar -cpzf $DESDIR/$FILENAME --directory="$SRCDIR" . --exclude=./folder_not_wanted      

echo "site files backed up: $DESDIR"
echo "use tar -xvzf to unzip"

To run the script, do this:


sh backup.sh

Development and tagged