MySql定时备份脚本

最近需要对某服务的数据库数据进行备份,因此参考网上教程完成数据库备份脚本.
因为服务的使用频率较低,因此设置定时任务,在每天的中午以及午夜时分进行备份操作.

1#!/bin/bash 2# 设置mysql的登录用户名和密码(根据实际情况填写) 3mysql_user="***" 4mysql_password="****" 5mysql_host="localhost" 6mysql_port="3306" 7mysql_charset="utf8mb4" 8 9# 备份文件存放地址(根据实际情况填写) 10backup_location=/home/app/***/sql_backup 11 12# 是否删除过期数据 13expire_backup_delete="ON" 14expire_days=7 15backup_time=`date +%Y%m%d%H%M` 16backup_dir=$backup_location 17welcome_msg="Welcome to use MySQL backup tools!" 18 19# 判断mysql实例是否正常运行 20mysql_ps=`ps -ef |grep mysql |wc -l` 21mysql_listen=`netstat -an |grep LISTEN |grep $mysql_port|wc -l` 22if [ [$mysql_ps == 0] -o [$mysql_listen == 0] ]; then 23 echo "ERROR:MySQL is not running! backup stop!" 24 exit 25else 26 echo $welcome_msg 27fi 28 29# 备份指定数据库中数据(此处假设数据库是mysql_backup_test) 30mysqldump -h$mysql_host -P$mysql_port -u$mysql_user -p$mysql_password -B mysql_backup_test> $backup_dir/mysql_backup_test-$backup_time.sql 31flag=`echo $?` 32if [ $flag == "0" ];then 33 echo "database mysql_backup_test success backup to $backup_dir/mysql_backup_test-$backup_time.sql.gz" 34else 35 echo "database mysql_backup_test backup fail!" 36fi 37 38# 删除过期数据 39if [ "$expire_backup_delete" == "ON" -a "$backup_location" != "" ];then 40 `find $backup_location/ -type f -mtime +$expire_days | xargs rm -rf` 41 echo "Expired backup data delete complete!" 42fi 43 44

以上是数据库备份脚本.

编辑定时任务:

1crontab -e 2# 添加定时任务(每天12:50以及23:50执行备份操作) 350 12,23 * * * cd /home/app/jinxd/;sh mysql_backup_test_backup.sh >> log.txt 2>>log.txt 4 5
下一篇:PowerShell: 入门

代码交流 2021