Created
November 12, 2020 17:31
-
-
Save chrisdkemper/eeadb32d8c8f3a580f1d726fd23d914f to your computer and use it in GitHub Desktop.
Backup a DB on a server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
function log { | |
echo "[`date +'%Y-%m-%d %H:%M:%S.%N'`] $1" | |
} | |
MYSQL_BACKUP_USER=$(grep DB_USERNAME ./../.env | awk -F= '{ print $2 }') | |
MYSQL_BACKUP_PASS=$(grep DB_PASSWORD ./../.env | awk -F= '{ print $2 }') | |
BACKUP_DIR=/var/mysql-backup/storage | |
EXCLUDED_DATABASES=(Database information_schema mysql performance_schema sys) | |
RETAIN_FOR_DAYS=365 | |
for DATABASE in `MYSQL_PWD="$MYSQL_BACKUP_PASS" /usr/bin/mysql -u "$MYSQL_BACKUP_USER" -e "SHOW DATABASES;" | cut -d ' ' -f 1`; do | |
for EXCLUDED in ${EXCLUDED_DATABASES[@]}; do | |
if [ "$DATABASE" == "$EXCLUDED" ]; then | |
log "Excluding backup of '$DATABASE'" | |
continue 2 | |
fi; | |
done | |
NOW=`date +"%Y-%m-%d"` | |
TARGET="$BACKUP_DIR/$NOW" | |
if [ ! -d "$TARGET" ]; then | |
mkdir -p "$TARGET" | |
fi; | |
log "Starting backup of '$DATABASE'" | |
MYSQL_PWD="$MYSQL_BACKUP_PASS" /usr/bin/mysqldump -u "$MYSQL_BACKUP_USER" "$DATABASE" | gzip > "$TARGET/$DATABASE-$NOW.sql.gz" | |
log "Completed backup of '$DATABASE'" | |
done | |
for FOLDER in `find "$BACKUP_DIR/" -type d -ctime +$RETAIN_FOR_DAYS`; do | |
if [[ "$FOLDER" != "$BACKUP_DIR"* ]]; then | |
log "Aborting deletion of backup folder '$FOLDER' due to directory mismatch" | |
continue | |
fi; | |
if [ -d "$FOLDER" ]; then | |
log "Removing expired backups in '$FOLDER'" | |
rm -rf "$FOLDER" | |
fi; | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment