Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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