Last active
June 26, 2023 04:25
-
-
Save eusonlito/bf7e27eb1732d81275cb to your computer and use it in GitHub Desktop.
Automate your MySQL backups
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
#!/bin/bash | |
# ------------------------------------- | |
# Databases backup with X days storage history | |
# | |
# User executing this script must have FULL permissions | |
# to mysql and mysqldump | |
# | |
# Use $HOME/.my.cnf to store MySQL auth | |
# | |
# This script is freely distributed under the GPL | |
# ------------------------------------- | |
echo "" | |
echo "START: "$(date "+%Y-%m-%d %H:%M:%S") | |
# Configuration | |
BACKUPDIR="/var/backups/mysql" # Backups Storage Folder | |
DAYS=7 # Store Backups X Days | |
DATE=$(date "+%Y%m%d") # Backup File Prefix | |
# Script execution | |
DATABASES="$(mysql -Bse "SHOW DATABASES" | grep -vwE "(information_schema|performance_schema)")" | |
for db in $DATABASES; do | |
dir="$BACKUPDIR/$db" | |
file="$dir/$DATE.sql.gz" | |
if [ ! -d "$dir" ]; then | |
install -d "$dir" | |
fi | |
echo "Processing $db into $file" | |
mysqldump \ | |
--single-transaction \ | |
--quick \ | |
--skip-events \ | |
--ignore-table=mysql.event \ | |
--routines \ | |
--triggers \ | |
--force \ | |
--add-drop-table \ | |
$db | gzip -9 > "$file" | |
done | |
find "$BACKUPDIR" -maxdepth 1 -mindepth 1 -type d | while read directory; do | |
for file in $(ls -t "$directory" | tail -n +$DAYS); do | |
echo -e "\n\nDeleted history backup $directory/$file" | |
rm -f "$directory/$file" | |
done | |
done | |
echo "END: "$(date "+%Y-%m-%d %H:%M:%S") | |
exit 0 |
Thank you. What is your case use the script? Cron, yeah?
Yes, it's executed as a cron job every day :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you. What is your case use the script? Cron, yeah?