mysql定时备份数据

备份脚本(生产环境已经使用,没有问题)

#!/bin/bash
# 设置mysql的登录用户名和密码(根据实际情况填写)
mysql_user="root"
mysql_password="123456"
mysql_host="localhost"
mysql_port="3306"
mysql_charset="utf8mb4"
mysql_shema="marshall"
# 备份文件存放地址(根据实际情况填写)
backup_location=/home/kilox/sql_backup

# 是否删除过期数据
expire_backup_delete="ON"
expire_days=30
backup_time=`date +%Y%m%d%H%M`
backup_dir=$backup_location
welcome_msg="Welcome to use MySQL backup tools!"

# 判断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 $welcome_msg
fi

# 备份指定数据库中数据(此处假设数据库是$mysql_shema)
mysqldump -h$mysql_host -P$mysql_port -u$mysql_user -p$mysql_password -B $mysql_shema> $backup_dir/$mysql_shema-$backup_time.sql
flag=`echo $?`
if [ $flag == "0" ];then
        echo "database $mysql_shema success backup to $backup_dir/$mysql_shema-$backup_time.sql.gz"
else
        echo "database $mysql_shema backup fail!"
fi

# 删除过期数据
if [ "$expire_backup_delete" == "ON" -a  "$backup_location" != "" ];then
        `find $backup_location/ -type f -mtime +$expire_days | xargs rm -rf`
        echo "Expired backup data delete complete!"
fi

定时任务

在 /etc/cron.d目录下面新建文件,文件中加入如下内容

# 添加定时任务(每天12:50以及23:50执行备份操作)
50 12,23 * * * cd /home/app/jinxd/;sh mysql_backup.sh >> log.txt 2>>log.txt
启动:/etc/init.d/cron start ( service cron start )
重启:/etc/init.d/cron restart ( service cron restart )
关闭:/etc/init.d/cron stop ( service cron stop )
posted @ 2020-12-02 09:55  fingersnow  阅读(120)  评论(0编辑  收藏  举报