Skip to content

Instantly share code, notes, and snippets.

@JeffreyHyer
Last active June 20, 2017 17:09
Show Gist options
  • Save JeffreyHyer/a27b22a1cbbee6255317a86b9a33e235 to your computer and use it in GitHub Desktop.
Save JeffreyHyer/a27b22a1cbbee6255317a86b9a33e235 to your computer and use it in GitHub Desktop.
Backup a MySQL database automatically via a cron task
#!/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
#!/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