mysql自动备份脚本

备份脚本

#!/bin/bash

#author cheng

#mysql数据自动备份

mysql_user="root"

mysql_password="passwprd"

mysql_host="localhost"

mysql_port="3306"

mysql_charset="utf8mb4"

#备份文件存放地址(根据实际情况填写)

backup_location=/usr/cheng/msg_manager/sql

#是否删除过期数据

expire_backup_delete="ON"

#过期时间设置

expire_days=7

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 [ [ m y s q l p s = = 0 ] − o [ mysql_ps == 0] -o [ mysqlps==0]−o[mysql_listen == 0] ]; then

echo "ERROR:MySQL is not running! backup stop!"

exit

else

echo $welcome_msg

fi

#备份指定数据库中数据

mysqldump -h m y s q l h o s t − P mysql_host -P mysqlhost−Pmysql_port -u m y s q l u s e r − p mysql_user -p mysqluser−pmysql_password -B msg_manager> b a c k u p d i r / m s g m a n a g e r − backup_dir/msg_manager- backupdir/msgmanager−backup_time.sql

flag=echo $?

if [ $flag == "0" ];then

echo "database msg_manager success backup to b a c k u p d i r / m s g m a n a g e r − backup_dir/msg_manager- backupdir/msgmanager−backup_time.sql"

else

echo "database msg_manager backup fail!"

fi

#删除过期数据

if [ " e x p i r e b a c k u p d e l e t e " = = " O N " − a " expire_backup_delete" == "ON" -a " expirebackupdelete"=="ON"−a"backup_location" != "" ];then
find $backup_location/ -type f -mtime +$expire_days | xargs rm -rf

echo "Expired backup data delete complete!"

fi

添加定时任务

复制代码
crontab -e
# 添加定时任务(每天12:50以及23:50执行备份操作)
50 12,23 * * * /usr/cheng/msg_manager/sql/sh/mysql_backup.sh >> /usr/cheng/msg_manager/sql/sh/exec.log 2>> /usr/cheng/msg_manager/sql/sh/exec_err.log

重启定时任务服务

复制代码
service crond restart
相关推荐
Johny_Zhao1 小时前
OpenClaw安装部署教程
linux·人工智能·ai·云计算·系统运维·openclaw
NineData1 小时前
NineData 迁移评估功能正式上线
数据库·dba
NineData7 小时前
数据库迁移总踩坑?用 NineData 迁移评估,提前识别所有兼容性风险
数据库·程序员·云计算
赵渝强老师9 小时前
【赵渝强老师】PostgreSQL中表的碎片
数据库·postgresql
全栈老石13 小时前
拆解低代码引擎核心:元数据驱动的"万能表"架构
数据库·低代码
倔强的石头_1 天前
kingbase备份与恢复实战(二)—— sys_dump库级逻辑备份与恢复(Windows详细步骤)
数据库
chlk1232 天前
Linux文件权限完全图解:读懂 ls -l 和 chmod 755 背后的秘密
linux·操作系统
舒一笑2 天前
Ubuntu系统安装CodeX出现问题
linux·后端
改一下配置文件2 天前
Ubuntu24.04安装NVIDIA驱动完整指南(含Secure Boot解决方案)
linux
碳基沙盒2 天前
OpenClaw 多 Agent 配置实战指南
运维