#!/bin/sh
#######################################################
#ShellName:mysql database and tables backup
#Author:zkg
#Created Time:2019-08-26
#Blog Address:https://blog.51cto.com/1009516
#######################################################

#调用系统函数库
. /etc/init.d/functions
#Define variables
BACKUPDIR=/data/mysqlbak/
MYSQLUSER=root
MYSQLPASSWD=DbApp
MYSQLSOCK=/data/mysql/tmp/mysql.sock
MYSQLCMD="/data/mysql/bin/mysql -u$MYSQLUSER -p$MYSQLPASSWD -S $MYSQLSOCK"
MYSQLDUMP="/data/mysql/bin/mysqldump -u$MYSQLUSER -p$MYSQLPASSWD -S $MYSQLSOCK -x -F -R"
DATABASELIST="$MYSQLCMD -e "show databases;"|sed 1d|egrep -v "information_schema|bin|innodb|mysql|soc""

for DBNAME in $DATABASELIST
do
if [ ! -d $BACKUPDIR/$DBNAME ];then
mkdir -p $BACKUPDIR/$DBNAME && \
action "Create a backup directory successfully and start backing up the database" /bin/true
else
action "The backup directory already exists. Start backing up the database." /bin/true &>/dev/null
fi
echo -e "\033[32mstarting backup $DBNAME databases\033[0m"
$MYSQLDUMP $DBNAME|gzip > $BACKUPDIR/$DBNAME/${DBNAME}$(date +%F%H%M%S).gz
RETVAL=$?
if [ $RETVAL -eq 0 ];then
action "$DBNAME database Successful backup" /bin/true
else
action "$DBNAME database failed backup" /bin/false
continue
fi
echo "starting backup tables from $DBNAME"
TABLELIST="$MYSQLCMD -e "show tables from $DBNAME"|sed 1d"
for TABLENAME in $TABLELIST
do
$MYSQLDUMP $DBNAME $TABLENAME|gzip > $BACKUPDIR/$DBNAME/${DBNAME}
${TABLENAME}_$(date +%F%H%M%S).gz
RETVAL=$?
if [ $RETVAL -eq 0 ];then
action "$TABLENAME table Successful backup" /bin/true
else
action "$TABLENAME table failed backup" /bin/false
continue
fi
done
done