linux下的MySQL自动备份脚本-第一版

写了个linux下的mysql备份脚本 这是第一版,只支持备份一个数据库,每天晚上2点用定时器把这个脚本跑一下就自动备份好了。后续会做可支持备份多个数据库,备份失败短信发送到手机,自动清除过期备份。

#!/bin/bash
#Script:backup_mysql
#Version:Release 1.0
#author:www.dba-china.com
#date:2011-10-26

backup_time=`date +%Y%m%d%H%M`  #定义备份详细时间
backup_Ymd=`date +%Y%m%d` #定义备份目录中的年月日时间
backup_7ago=`date -d '7 days ago' +%Y%m%d` #七天之前的日期
backup_dir=/backup/mysql/$backup_Ymd  #备份文件夹全路径
backup_database="dba-china" #要备份的数据库名称
mysql_user="root"
mysql_password="root"
#mysql_host="localhost"
#mysql_port="3306"

#判断MYSQL是否启动,mysql没有启动则备份退出
mysql_ps=`ps -ef |grep mysql |wc -l`
mysql_listen=`netstat -an |grep LISTEN |grep $mysql_port|wc -l`
if [ [$mysql_ps == 0] -o [$mysql_listen == 0] ]; then
        echo "ERROR:MySQL is not running! backup stop!"
        exit;
else
        echo "MySQL running ok!"
fi

#连接到mysql数据库,无法连接则备份退出
mysql -u$mysql_user -p$mysql_password <<end
use mysql;
select host,user from user where user='root' and host='localhost';
exit
end

flag=`echo $?`
if [ $flag != "0" ]; then
        echo "error:Can't connect mysql server! backup stoped!"
        exit;
else
        echo "MySQL connect ok! Backup start......"
        #db=`echo $backup_database |cut -d ',' -f1`
        db=$backup_database       
        if [ $db == '' ];then
                echo "ERROR:no database to backup!"
        else
                echo "database $db backup start..."
                `mkdir -p $backup_dir`
                `mysqldump -u$mysql_user -p$mysql_password $db > $backup_dir/$db$backup_time.sql`
                echo "database $db backup success!"
        fi

fi

查看原文: http://bbs.dba-china.com/thread-206-1-1.html

你可能感兴趣的:(linux)