自动化运维——MySQL备份脚本(二)

使用if语句编写MySQL备份脚本

 代码:

#!/bin/bash
#auro backup mysql db
#by steve yu 2019
#define backup path 

BAK_DIR=/data/backup/`date +%Y%m%d`
MYSQLUSR=root
MYSQLPW=Root123
MYSQLCMD=/usr/bin/mysqldump
#ne是代表not equals,$UID是代表用户,0为root用户
#这边时表示如果不是root用户,则退出
if [[ $UID -ne 0 ]];then
        echo "Must to be use root for exec Shell."
        exit
fi

if [[ ! -d $BAK_DIR ]];then
        mkdir -p $BAK_DIR
        echo -e "\033[32mThe $BAK_DIR create successfully!\033[0m"
else
        echo -e "\033[32mThis $BAK_DIR is exists...\033[0m"
fi

$MYSQLCMD -u$MYSQLUSR -p$MYSQLPW --all-databases > $BAK_DIR/backup.sql

if [[ $? -eq 0 ]];then

        echo -e "\033[32mMysql backup successfully!\033[0m"

else

        echo -e "\033[32mMysql backup failed!\033[0m"

fi

截图:

运行结果:

 sh -n 文件名,检查脚本有没有问题

crontab -e添加定时任务

0    0 * * * /bin/bash /root/auto_backup_mysql.sh >> /tmp/mysql_bak.log 2>&1

今日作业,修改上脚本,使得mysql当天不备份2次

修改后bash脚本

BAK_DIR=/data/backup/`date +%Y%m%d`
MYSQLUSR=root
MYSQLPW=Root123
MYSQLCMD=/usr/bin/mysqldump
#ne是代表not equals,$UID是代表用户,0为root用户
#这边时表示如果不是root用户,则退出
if [[ $UID -ne 0 ]];then
        echo "Must to be use root for exec Shell."
        exit
fi

if [[ ! -d $BAK_DIR ]];then
        mkdir -p $BAK_DIR
        echo -e "\033[32mThe $BAK_DIR create successfully!\033[0m"
else
        echo -e "\033[32mThis $BAK_DIR is exists...\033[0m"
fi

if [[ ! -f $BAK_DIR/backup.sql ]];then
        $MYSQLCMD -u$MYSQLUSR -p$MYSQLPW --all-databases > $BAK_DIR/backup.sql
        if [[ $? -eq 0 ]];then
                echo -e "\033[32mMysql backup successfully!\033[0m"
        else
                echo -e "\033[32mMysql backup failed!\033[0m"
        fi
else
        echo -e "\033[32mToday is already backuped\033[0m"
fi

 

posted @ 2019-08-19 11:58  SteveYu  阅读(446)  评论(0编辑  收藏  举报