Skip to content

Instantly share code, notes, and snippets.

@jschnasse
Created November 8, 2018 09:01
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jschnasse/2652bfad3dc8625dc00b1826a9c66409 to your computer and use it in GitHub Desktop.
#! /bin/bash
scriptdir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $scriptdir
source variables.conf
function init(){
echo "Init"
mkdir -p $BACKUP/mysql
echo "Done!"
}
function backup(){
SNAPSHOT=`date +%Y%m%d-%H%M%S`
mysqldump -u root -p$PASSWORD --events --all-databases > $BACKUP/mysql/$SNAPSHOT.sql
}
function clean(){
echo "Clean"
# The amount of snapshots we want to keep.
LIMIT=30
# Get a list of snapshots that we want to delete
len=`ls -tr $_BACKUP/mysql/|wc -l`
num=`expr $len - $LIMIT`
if [ $num -gt 0 ]
then
SNAPSHOTS=`ls -tr $_BACKUP/mysql/|head -$num`
# Loop over the results and delete each snapshot
for SNAPSHOT in $SNAPSHOTS
do
echo "Deleting snapshot: $SNAPSHOT"
rm -rf $BACKUP/mysql/$SNAPSHOT
done
fi
echo "Done!"
}
function restore(){
SNAPSHOT=123
mysql -u root $PASSWORD -p < $SNAPSHOT.sql
}
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-i|--init)
init;
shift # past argument
;;
-b|--backup)
backup;
shift # past argument
;;
-r|--restore)
restore
shift # past argument
;;
-c|--clean)
clean
shift # past argument
;;
*)
# unknown option
echo "Use --init|--backup|--clean|--restore"
;;
esac
shift # past argument or value
done
30 2 * * * /full/path/to/backup-db.sh -b >> /keep/logs/backup-db.log 2>&1
0 2 * * * /full/path/to/backup-db.sh -c >> /keep/logs/backup-db.log 2>&1
PASSWORD=yourMysqlRootPassword
BACKUP=yourBackupFolder
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment