Skip to content

Instantly share code, notes, and snippets.

@elfeffe
Forked from colinmollenhour/mysqlsnapshot.sh
Created October 18, 2016 09:10
Show Gist options
  • Save elfeffe/cbc43632610d87c9f88c331611d943aa to your computer and use it in GitHub Desktop.
Save elfeffe/cbc43632610d87c9f88c331611d943aa to your computer and use it in GitHub Desktop.
MySQL Snapshot Script
#!/bin/bash
DBNAME=mwe
SNAPSHOT_DAYS=7
ARCHIVE_DAYS=60
mysqldump=/usr/bin/mysqldump
gzip=/bin/gzip
function error() {
echo $1 >> $logfile.tmp
cat $logfile.tmp
cat $logfile.tmp >> $logfile
rm $logfile.tmp
exit 1
}
cd /root/mysql-snapshots || { echo "Snapshots directory does not exist."; exit 1; }
logfile=$(readlink -f mysqlsnapshot.log)
name=$(date +%b-%d-%k)
aname=$(date +%b-%d)
year=$(date +%Y)
snapshotFile=snapshots/$year/$name.sql.gz
archiveFile=archive/$year-$aname.sql.gz
[ -d snapshots ] || mkdir snapshots || error "Could not create directory 'snapshots'"
[ -d snapshots/$year ] || mkdir snapshots/$year || error "Could not create directory 'snapshots/$year'"
[ -d archive ] || mkdir archive || error "Could not create directory 'archive'"
echo "Starting dump at $(date)" > $logfile.tmp
$mysqldump --single-transaction --quick --routines --events $DBNAME 2>> $logfile.tmp > latest-$DBNAME.sql
error=$?
if [ $error -eq 0 ]; then
echo "Compressing dump file..." > $logfile.tmp
$gzip --rsyncable --force latest-$DBNAME.sql || error "Could not gzip dump file: $?"
cp -l latest-$DBNAME.sql.gz $snapshotFile
if [ $ARCHIVE_DAYS -gt 0 ] && [ $(($(date +%d | sed 's/^0*//') % 10)) == 0 ] && [ ! -f $archiveFile ]; then
echo "Archiving to $archiveFile" >> $logfile.tmp
cp -l $snapshotFile $archiveFile
fi
echo -e "Completed at $(date)\n\n" >> $logfile.tmp
cat $logfile.tmp >> $logfile
rm $logfile.tmp
# Cleanup old snapshots
find snapshots -mtime +$SNAPSHOT_DAYS -exec rm {} \;
find archive -mtime +$ARCHIVE_DAYS -exec rm {} \;
find . -type d -empty -exec rmdir {} \;
cat $logfile.tmp >> $logfile
rm $logfile.tmp
else
error "Error creating MySQL dump for $year/$name: $error"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment