1. 程式人生 > >用if寫一個備份mysql的指令碼

用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.