Created
May 12, 2011 22:03
-
-
Save ViktorStiskala/969558 to your computer and use it in GitHub Desktop.
Simple MySQL backup script
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 | |
# MySQL backup script | |
# Creates database dump file for each database. | |
# Created: 2010-09-27 | |
# config | |
BACKUP_USER=backup | |
BACKUP_DIR=/var/backups/mysql | |
LOGFILE=/var/log/mysql_backup | |
error() | |
{ | |
echo $1 1>&2 | |
exit 1 | |
} | |
dump() | |
{ | |
tmpfile=`mktemp` | |
trap "rm -f \"$tmpfile\"; exit 0" SIGINT SIGTERM SIGHUP SIGQUIT | |
mysqldump --skip-comments -u "$BACKUP_USER" "$1" > "$tmpfile" 2>>$LOGFILE | |
# check dump error code | |
if [ $? -gt 0 ]; | |
then | |
rm -f "$2" | |
error "Backup failed for $1, see logfile." | |
fi | |
# compress file | |
bzip2 --best "$tmpfile" | |
tmpfile="${tmpfile}.bz2" | |
diff=$(diff -N "$tmpfile" "${2}.bz2") | |
if [ "$diff" == "" ]; | |
then | |
echo "No need to update: $1" | |
rm "$tmpfile" | |
else | |
mv "$tmpfile" "${2}.bz2" | |
# set permissions | |
chmod 640 "${2}.bz2" | |
echo "Dump finished: $1" | |
fi | |
} | |
# get all database names except "information_schema" | |
databases=$(mysql -u "$BACKUP_USER" -NBe "SHOW DATABASES;" | grep -v "information_schema") | |
# create backup directory if it doesn't exists | |
mkdir -p "$BACKUP_DIR" | |
if [ $? -gt 0 ]; | |
then | |
error "Cannot create backup directory, exiting" | |
fi | |
# for each database | |
pids="" | |
for db in $databases; | |
do | |
cur_file="${BACKUP_DIR}/${db}" | |
# rm -f "$cur_file.bz2" | |
dump "$db" "$cur_file" & | |
pids="$pids $!" | |
done | |
# wait for all processes to finish | |
wait $pids |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment