Last active
June 20, 2017 17:09
-
-
Save JeffreyHyer/a27b22a1cbbee6255317a86b9a33e235 to your computer and use it in GitHub Desktop.
Backup a MySQL database automatically via a cron task
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 | |
############################ | |
# Usage: ./mysql_backup.sh | |
# | |
# Crontab: 0 * * * * bash /home/[USERNAME]/mysql_backup.sh (hourly at the top of the hour) | |
# 0 0 * * * bash /home/[USERNAME]/mysql_backup.sh (daily at midnight) | |
############################ | |
# The current date and time (e.g. 201706141700, YYYYMMDDHHMM) | |
ts=$(date +%Y%m%d%H%M) | |
# Backup a specific database | |
# - Stream the SQL output to gzip for on-the-fly compression | |
mysqldump --defaults-extra-file=/home/[USERNAME]/mysql.cnf --single-transaction --quick --lock-tables=false [DATABASE] | gzip -9 > /home/[USERNAME]/mysql_backup/hourly/[DATABASE]_"$ts".sql.gz | |
# Clean up old backups automatically | |
# - Find and delete (-delete) all files (-type f) | |
# that are older than 7 days (-mtime +7) | |
# and end in .sql.gz (-name '*.sql.gz') | |
find /home/[USERNAME]/mysql_backup/hourly -type f -mtime +7 -name '*.sql.gz' -delete |
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 | |
####################### | |
# Usage: ./rsync.sh | |
# | |
# Sync backup files from a remote server to the local machine | |
# to act as a secondary backup in the event of hardware failure | |
# or otherwise being unable to access the primary backup | |
####################### | |
rsync -avz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --progress [USER]@[REMOTE HOST]:/home/[USER]/mysql_backup/ [LOCAL PATH TO SAVE BACKUPS] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment