用if写一个备份mysql的脚本

#!/bin/bash
# 备份数据库
BAK_DIR=/data/backup/`date +%Y%m%d`
MYSQLDB=dexin
MYSQLUSER=root
MYSQLPW=123456
MYSQLCMD=/usr/bin/mysqldump

# 判断是否是root执行的
if [ $UID -ne 0 ];then
    echo "Must use root"
    exit
fi

# 判断目录是否存在
if [ ! -d $BAK_DIR ];then
    mkdir -p $BAK_DIR
    echo "The $BAK_DIR create success."
else
    echo "The $BAK_DIR is exist. "
fi

# 进行备份操作
$MYSQLCMD -u$MYSQLUSER -p$MYSQLPW $MYSQLDB >$BAK_DIR/$MYSQLDB.sql

if [ $? -eq 0 ];then
    echo -e "\033[32m The Mysql $MYSQLDB Backup Success.\033[0m "
else
    echo -e "\033[32m The Mysql $MYSQLDB Backup Failed.\033[0m "
fi 

有意思的,创建用户,判断是否是root 。判断是否成功。定义变量。输出颜色。判断目录,创建目录等。

写一个定时器,

# 备份mysql
0 0 * * * /bin/bash /home/shell/backup.sh >> /tmp/mysql_bak.log 2>&1

查看备份日志

# cat /tmp/mysql_bak.log 
The /data/backup/20181128 is exist. 
mysqldump: [Warning] Using a password on the command line interface can be insecure.
 The Mysql dexin Backup Success.
posted @ 2018-11-28 20:14  TBHacker  阅读(413)  评论(0编辑  收藏  举报