Skip to content

Backup Script

Ron Rennick edited this page Jul 24, 2019 · 2 revisions

If you want to backup your databases using cron, there is a bash script shardb-back.sh included below.

  1. Create a folder under your linux user account called backups
  2. Create a text file called db-list.txt in the backups folder
$ for D in 0 1 2 3 4 5 6 7 8 9 a b c d e f global; do \
echo $D >> db-list.txt \
done
  1. Upload shardb-back.sh to the backups folder
  2. Set the executable permission on shardb-back.sh

chmod +x shardb-back.sh

  1. schedule your backup job in cron with the command

$HOME/backups/shardb-back your_db_user your_db_password

Each set of backups will be stored in a date based directory under the backups directory (ex. /home/webaccount/backups/2019-01-31). The script automatically purges off the backups from 7 days prior. As long as the script is scheduled daily, all aged backups will be removed.

shardb-back.sh

#!/bin/bash
#
# basic parameter checks
#
if [ "$1" = "" -o "$2" = "" ]; then
	echo Usage: $0 dbuser dbpassword
	exit
fi
#
# set the variables
#
DBSTARTDIR=`pwd`
cd ${0%/*}
DBSCRIPTDIR=`pwd`
DBLIST=`cat $DBSCRIPTDIR/db-list.txt`
ZIPDIR=$DBSCRIPTDIR/`date +%F`
#
# final prep work & validation
#
if [ ! -e $ZIPDIR ]; then
	mkdir $ZIPDIR
fi
cd $ZIPDIR
echo Entering `pwd`
#
# backup & zip
#
for D in $DBLIST ; do
	mysqldump -u $1 -p$2 --skip-lock-tables $D > $D.sql && \
		zip -mq $D.zip $D.sql && \
		echo created $D.zip
done
#
# clean up
#
echo Leaving `pwd`
echo Entering $DBSCRIPTDIR
cd $DBSCRIPTDIR
OLDBACKDIR=`date -d "-7 days" +%F`
if [ -d $OLDBACKDIR ]; then
	rm -rf $OLDBACKDIR && \
		echo Removed old backup directory $OLDBACKDIR
fi
echo Leaving `pwd`
cd $DBSTARTDIR
Clone this wiki locally