升级数据库脚本(加入事务)

#!/bin/bash

#ip=x.x.x.x
#pass='x.x.x.x'
pass='x.x.x.x'
time=`date +%Y%m%d-%H%M`
db_path=/root/code/xizang_PAD_project/PHP_business_server/tfcms/upgrade/db/
db_name=tf_syberos_cms
db_bak=/usr/local/src/backup/$db_name-$time\.sql

#Determine the results
result() {
    if [ $? != 0 ];then
        echo -e "\033[31m$1 $faild\033[0m" && exit 1
    else
        echo -e "\033[32m$1 $ok\033[0m"
    fi
}

#usage $1 is remote ip , $2 is sql file
usage() {
if [ $# -lt 2 ];then
    echo -e "\033[31m usage: sh $0 ip sql_file\033[0m" 
    echo -e "\033[31m example: sh $0 172.16.160.99 v1.0.0-v1.1.0.txt \033[0m" 
    echo -e "\033[31m explain: 升级主机要配置ssh免密,可以使用auto_ssh.sh \033[0m" && exit 2
fi
}

#Backup remote database
backup_db() {
    ok="backup db ok !";faild="backup db faild !"
    ssh root@$1 "mysqldump -uroot -p$pass -R --opt $db_name > $db_bak"
    result

}

#sql files add transaction
add_transaction() {
    ok="add transaction ok !";faild="add transaction faild !"
    grep "start transaction" $db_path$2
    if [ $? != 0 ];then
        sed -i '1i\start transaction;' $db_path$2
        result
    fi
    grep "commit" $db_path$2
    if [ $? != 0 ];then
        echo "commit;" >> $db_path$2
        result
    fi
}

# Import sql 
import_sql() {
    ok="sql execution ok !";faild="sql execution faild !"
    if [ -f $db_path/$2 ];then
        mysql -uroot -p$pass -h$1 tf_syberos_cms < $db_path$2 
        result
    else
        echo -e "\033[31m $db_path/$2 file no exist ! \033[0m" && exit 1
    fi
}

#main function
main() {
    usage $1 $2
    backup_db $1
    add_transaction $1 $2
    import_sql $1 $2
}

main $1 $2

 

posted @ 2018-05-15 10:55  wangmo  阅读(216)  评论(0编辑  收藏  举报