Skip to content

Instantly share code, notes, and snippets.

@diegogurpegui
Last active January 3, 2019 14:09
Show Gist options
  • Save diegogurpegui/db14475561ecf7520d6832fce9cdeffe to your computer and use it in GitHub Desktop.
Save diegogurpegui/db14475561ecf7520d6832fce9cdeffe to your computer and use it in GitHub Desktop.
MySQL backup script. Could be used to automate the process with cron.
0 0 * * * sh /route/to/script/mysql_backup.sh >> /var/log/myapp/mysql_backup.log 2>&1
#!/bin/bash
#----------------------------------------
# OPTIONS
#----------------------------------------
USER='root' # MySQL User
PASSWORD='rootpass' # MySQL Password
DATABASE='myapp' # Databases to backup, comma separated. 'All' or '' means all databases.
DAYS_TO_KEEP=30 # 0 to keep forever
GZIP=1 # 1 = Compress
BACKUP_PATH='/var/backups/myapp'
DATE=`date '+%Y%m%d-%H%M'`
#----------------------------------------
# Create the backup folder
if [ ! -d $BACKUP_PATH ]; then
mkdir -p $BACKUP_PATH
fi
# Get list of database names
databases=`mysql -u $USER -p$PASSWORD -e "SHOW DATABASES;" | tr -d "|" | grep -v Database`
for db in $databases; do
if [ $db == 'information_schema' ] || [ $db == 'performance_schema' ] || [ $db == 'mysql' ] || [ $db == 'sys' ]; then
echo "Skipping system database: $db"
continue
fi
if [ $DATABASE != '' ] && [ $DATABASE != 'All' ] && [[ $db != $DATABASE ]]; then
echo "Skipping database: $db"
continue
fi
date=$(date -I)
if [ "$GZIP" -eq 0 ] ; then
echo "Backing up database: $db without compression"
mysqldump -u $USER -p$PASSWORD --databases $db > $BACKUP_PATH/$db-$DATE.sql
else
echo "Backing up database: $db with compression"
mysqldump -u $USER -p$PASSWORD --databases $db | gzip -c > $BACKUP_PATH/$db-$DATE.gz
fi
done
# Delete old backups
if [ "$DAYS_TO_KEEP" -gt 0 ] ; then
echo "Deleting backups older than $DAYS_TO_KEEP days"
find $BACKUP_PATH/* -mtime +$DAYS_TO_KEEP -exec rm {} \;
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment