#!/bin/bash
#auto backup any one or all db
#by zhaoyanfeng
#2017-8-15 11:17:54
#defined
ALL_DB=`mysql -uroot -p123456 -e "show databases;"| grep -v Database | xargs -n 1`
MYSQL_USER=root
MYSQL_PASSWD="123456"
MYSQL_BACKUP_DIR=/home/zhaoyanfeng/backup_mysql
if [ -z $1 ]; then
echo -e "\033[31mUsage: /bin/bash if_backup_mysql.sh [ dbname | all ]\033[0m"
echo -e "\033[31mYou can use /bin/bash if_backup_mysql.sh help to get help\033[0m"
exit 5
fi
if [ $# -gt 1 ]; then
echo -e "\033[31mUsage: /bin/bash if_backup_mysql.sh [ dbname | all ]\033[0m"
echo -e "\033[31mYou can use /bin/bash if_backup_mysql.sh help to get help\033[0m"
exit 5
fi
if [ $1 == "help" ]; then
echo -e "\033[32m------------------------------\033[0m"
echo -e "\033[31mSelect one dbname or all to backup as blow.\033[0m"
echo $ALL_DB | xargs -n 1
echo -e "\033[32m------------------------------\033[0m"
echo all
echo -e "\033[32m------------------------------\033[0m"
echo -e "\033[31mUsage: /bin/bash if_backup_mysql.sh [ dbname | all ]\033[0m"
elif mysql -u$MYSQL_USER -p$MYSQL_PASSWD -e ‘show databases;‘ | grep -v Database | grep $1 &>/dev/null; then
if [ -f $MYSQL_BACKUP_DIR/$1_`date +%F`.sql ]; then
echo "have exist backup file,so backup old file to RANDOM.bak" && mv $MYSQL_BACKUP_DIR/$1_`date +%F`.sql $MYSQL_BACKUP_DIR/$1_`date +%F`_$RANDOM.sql.bak && mysqldump -u$MYSQL_USER -p$MYSQL_PASSWD $1 > $MYSQL_BACKUP_DIR/$1_`date +%F`.sql && echo -e "\033[33mcongratulations!!!\033[0m"
elif [ $UID -ne 0 ]; then
echo "Please use root account to bakcup mysql databases!"
exit 5
else
mysqldump -u$MYSQL_USER -p$MYSQL_PASSWD $1 > $MYSQL_BACKUP_DIR/$1_`date +%F`.sql && echo -e "\033[33mcongratulations!!!\033[0m"
fi
elif [ $1 == "all" ]; then
if [ $UID -ne 0 ]; then
echo "Please use root account to bakcup mysql databases!"
exit 5
elif [ -f $MYSQL_BACKUP_DIR/all_`date +%F`.sql ]; then
echo "have exist backup file,so backup old file to RANDOM.bak" && mv $MYSQL_BACKUP_DIR/$1_`date +%F`.sql $MYSQL_BACKUP_DIR/$1_`date +%F`_$RANDOM.sql.bak && mysqldump -u$MYSQL_USER -p$MYSQL_PASSWD --all-databases > $MYSQL_BACKUP_DIR/all_`date +%F`.sql && echo -e "\033[33mcongratulations!!!\033[0m" else
mysqldump -u$MYSQL_USER -p$MYSQL_PASSWD --all-databases > $MYSQL_BACKUP_DIR/all_`date +%F`.sql && echo -e "\033[33mcongratulations!!!\033[0m"
fi
else
echo "Please check if your input is correct or not."
fi