Skip to content

Instantly share code, notes, and snippets.

@stevegrunwell
Last active December 14, 2017 21:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stevegrunwell/e71a4ebdd0bada440cbe95b222161d1d to your computer and use it in GitHub Desktop.
Save stevegrunwell/e71a4ebdd0bada440cbe95b222161d1d to your computer and use it in GitHub Desktop.
Dump each MySQL database and send its backup to Amazon S3. https://engineering.growella.com/automatic-database-backups-amazon-s3/
#!/bin/bash
#
# Backup local databases to Amazon S3.
#
# This script takes a single argument: an S3 bucket name with optional path.
#
# Usage:
# database-backup.sh backup.example.com
# database-backup.sh backup.example.com/some/path
#
# Based on https://gist.github.com/2206527
if [ $# -lt 1 ]; then
echo -e ""
echo -e "Error: You must specify an S3 bucket."
echo -e ""
echo -e "Examples:"
echo -e " backups.example.com"
echo -e " backups.example.com/some/path"
echo -e ""
exit 1;
fi;
bucket="s3://$1"
echo -e "Beginning database backup..."
# List all the databases
databases=`mysql --login-path=database-backup -e "SHOW DATABASES;" \
| tr -d "| " \
| grep -v "\(Database\|information_schema\|performance_schema\|mysql\|test\|sys\)"`
# Feedback
echo -e "Dumping to \e[1;32m$bucket/\e[00m"
# Loop the databases
for db in $databases; do
# Define our filenames
filename="$db.sql.gz"
tmpfile="/tmp/$filename"
object="$bucket/databases/$filename"
# Feedback
echo -e "\e[1;34m$db\e[00m"
# Dump and zip
echo -e " creating \e[0;35m$tmpfile\e[00m"
mysqldump --login-path=database-backup --force --opt --databases "$db" | gzip -c > "$tmpfile"
# Upload
echo -e " uploading..."
s3cmd put "$tmpfile" "$object"
# Delete
rm -f "$tmpfile"
done;
# Job is complete.
echo -e "\e[1;32mDatabase backup completed successfully!\e[00m"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment