Skip to content

Instantly share code, notes, and snippets.

@eusonlito
Last active June 26, 2023 04:25
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eusonlito/bf7e27eb1732d81275cb to your computer and use it in GitHub Desktop.
Save eusonlito/bf7e27eb1732d81275cb to your computer and use it in GitHub Desktop.
Automate your MySQL backups
#!/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
@polozhevets
Copy link

Thank you. What is your case use the script? Cron, yeah?

@eusonlito
Copy link
Author

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