Skip to main content

We wrote tutorial how to crate cron jobs in CPanel and now we're continuing with instructions for creating a simple bash website backup script that works on Linux hosting environment.

- Advertisement -

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
 
DATE=$(date -I)
BASEBCKPPATH="/home/account/backup"
SITEDIRNAME="sitename"
DESTINATIONDIR="$BASEBCKPPATH/$DATE/$SITEDIRNAME" #e.g. /home/account/backup/2012-09-22/sitename
ERRORLOG=$DESTINATIONDIR/error.log
DBNAME="account_dbname"
DBUSER="account_name"
DBPASS="password"
 
# Delete all previous backups for the same date and site if exist
if [ -d "$DESTINATIONDIR" ]; then
  rm -rf $DESTINATIONDIR
fi
 
# Create backup directory if it doesn't exist, e.g. /home/account/backup/2012-09-14/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.

- Advertisement -
- Advertisement -

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

- Advertisement -