Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple backup script1. Dump MySQL tables into tmp folder2. Archive www, etc and tmp_sql dirs into one tarball3. Remove old archives4. Optional: mirror backups dir to remote server over ftp (lftp)5. Optional: chown backups dir
USER="backuper" #MySQL user
PASSWORD="password" #MySQL password
DBTMP="/tmp/mysqldump/" #temporary dir for mysqldump
EXCLUDE_FILE="exclude.txt" #exclude files and dirs
TARGETDIR="/var/www/ /var/data/ /var/gitrepos/ /opt/nginx/ /etc/apache2/" #dirs to backup
BACKUPDIR="/var/backups/local/" #backup storage
DAYSOLD="3" #remove old backups
DAYSOLD_W="7" #remove old backups weekly
DAYSOLD_M="31" #remove old backups monthly
NAME="backup-full-" #name prefix of archive
DAYOFMONTH=$(date +%d)
DAYOFWEEK=$(date +%u)
rm -rf $DBTMP/*
mkdir -p $DBTMP
mkdir -p $BACKUPDIR/monthly/
mkdir $BACKUPDIR/weekly/
databases=`mysql --user=$USER --password=$PASSWORD -e "SHOW DATABASES;" | tr -d "| " | grep -v Database`
for db in $databases; do
if [[ "$db" != "information_schema" ]] && [[ "$db" != _* ]] && [[ "$db" != "performance_schema" ]] ; then
echo "Dumping database: $db"
mysqldump --force --opt --user=$USER --password=$PASSWORD --databases $db > $DBTMP/`date +%Y-%m-%d`.$db.sql
if [ $DAYOFMONTH -eq "1" ] ; then #if new month begin
tar -zcf $BACKUPDIR/monthly/$NAME`date +%Y-%m-%d`.tar.gz -X $EXCLUDE_FILE $TARGETDIR $DBTMP
elif [ $DAYOFWEEK -eq "1" ] ; then #else if new week begin
tar -zcf $BACKUPDIR/weekly/$NAME`date +%Y-%m-%d`.tar.gz -X $EXCLUDE_FILE $TARGETDIR $DBTMP
tar -zcf $BACKUPDIR/$NAME`date +%Y-%m-%d`.tar.gz -X $EXCLUDE_FILE $TARGETDIR $DBTMP
find $BACKUPDIR -maxdepth 1 -type f -mtime +$DAYSOLD -name "$NAME*" -print0 | xargs -0 rm -f #rm daily
find $BACKUPDIR/weekly/ -maxdepth 1 -type f -mtime +$DAYSOLD_W -name "$NAME*" -print0 | xargs -0 rm -f #rm weekly
find $BACKUPDIR/monthly/ -maxdepth 1 -type f -mtime +$DAYSOLD_M -name "$NAME*" -print0 | xargs -0 rm -f #rm monthly
/usr/bin/lftp -f /root/backup.x #optional sync with remote server
chown -R user:user $BACKUPDIR #optional chown
Copy link

rhamdeew commented Sep 2, 2014

Поправил небольшой баг с удалением предыдущих бэкапов.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment