No matter whether you maintenance one or more websites you need to backup your data periodically. Here are instructions for creating a simple bash website backup script that works on Linux hosting environment.
What does the script do
- Check if backup folder already exists
- Create if the backup folder exist
- Backup website files
- Backup website database
- Output errors to the error.log file
Create a file, copy/paste the following bash code and change variables to suit your environment:
#!/bin/sh
# Cron job runs with:
# bash /home/account/backup/backup-sitename.sh
SITEDIRNAME="sitename"
DBNAME="account_dbname"
DBUSER="account_name"
DBPASS="password"
BASEBCKPPATH="/home/account/backup"
DATE=$(date -I)
DESTINATIONDIR="$BASEBCKPPATH/$DATE/$SITEDIRNAME" #e.g. /home/account/backup/2012-07-29/sitename
ERRORLOG=$DESTINATIONDIR/error.log
# Delete all previous backups
if [ -d "$DESTINATIONDIR" ]; then
rm -rf $DESTINATIONDIR
fi
# Create backup directory if it doesn't exist, e.g. /home/account/backup/2012-07-29/sitename
if [ ! -d "$DESTINATIONDIR" ]; then
mkdir -p $DESTINATIONDIR
fi
# Backup site folder
tar -czf $DESTINATIONDIR/${SITEDIRNAME}_${DATE}.tgz -C /home/account/addon ./$SITEDIRNAME 2> $ERRORLOG
# Backup site database
mysqldump -u $DBUSER -p$DBPASS -h localhost $DBNAME| gzip -9 > $DESTINATIONDIR/${DBNAME}_${DATE}.sql.gz 2> $ERRORLOG
After you create the script, configure cron jobs.
Explanation
rm -rf $DESTIONATIONDIR
Delete directory and all subfolders
mkdir -p $DESTIONATION
-p option is here to create full backup path, i.e. all folders in the path if they don’t exist
tar -czf …
-czf performs compression and gziptar
… -C /home/account/addon …
This part here is tricky, the tar command works with current folder and we’re telling it to change current folder.
… 2> $ERRORLOG
Outputs error(s) to the error.log file
