Created
February 21, 2013 00:34
-
-
Save rhutchison/5000980 to your computer and use it in GitHub Desktop.
script I find useful for backing up mysql databases.
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
MYSQL_USER="root" | |
MYSQL_PASS="" |
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/sh | |
#set -x | |
. /root/.mysql_access | |
# Directory where you want the backup files to be placed | |
path="/usr/backups/$(hostname)" | |
# MySQL Username and password | |
userpassword=" --user=${MYSQL_USER} --password=${MYSQL_PASS}" | |
# Databases excluded from backup | |
exclude="test information_schema" | |
# MySQL dump options | |
dumpoptions=" --quick --add-drop-database --add-drop-table --add-locks --disable-keys --extended-insert --routines --triggers --lock-tables" | |
# Unix Commands | |
chmod="$(which chmod)" | |
chown="$(which chown)" | |
find="$(which find)" | |
gzip="$(which gzip)" | |
mv="$(which mv)" | |
mysql="$(which mysql)" | |
mysqldump="$(which mysqldump)" | |
# Get all database list first | |
databases="$(${mysql} ${userpassword} -Bse 'show databases')" | |
# Create our backup directory if not already there | |
mkdir -p ${path}/mysql | |
if [ ! -d ${path}/mysql ]; then | |
echo "Not a directory: ${path}/mysql" | |
exit 1 | |
fi | |
$chown -R 0:0 ${path} | |
$chmod 0640 ${path} | |
$chmod 0640 ${path}/mysql | |
# Dump all of our databases | |
echo "Dumping MySQL Databases" | |
for database in $databases | |
do | |
skipdb=0 | |
for x in $exclude | |
do | |
[ "$database" = "$x" ] && skipdb=1 || : | |
done | |
if [ "$skipdb" = "0" ]; then | |
file="$(date +"%Y%m%d_%H")_${database}.sql.gz" | |
echo "Backup: ${database} (${file})" | |
$mysqldump $userpassword $dumpoptions $database | $gzip -9 > ${path}/mysql/${file}.tmp | |
$mv -f ${path}/mysql/${file}.tmp ${path}/mysql/${file} | |
fi | |
done | |
# Remove backups older than 5 days | |
$find -E ${path}/mysql -regex '.*(0[1-9]|[12][0-9])_.*' -type f -mtime +5d -exec rm -f {} \; | |
$find ${path}/mysql -type f -mtime +60d -exec rm -f {} \; | |
exit; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment