Example of shell script to back up MySQL database regularly under Linux every day

foreword

Hello everyone, this is Changqing. Recently, Changqing has built a new website. It happens to be a script to automatically back up the mysql database at regular intervals. Record it and give it to your friends as a reference.

start of text

Changqing will not be bb here, the script will be released directly for everyone, and
each paragraph of Changqing has been annotated

#!/bin/bash
  
#定义备份路径
BAKUPPATH=/data/bakup/db
#获取当前时间
DATETIME=$(date +%Y-%m-%d_%H%M%S)

#数据库主机地址(填ip也行)
HOST=localhost
#数据库用户名
DB_NAME=用户名
#数据库密码
DB_PWD=密码
#需要备份的数据库名
DATABASE=haitangw_cc

#检测备份目录是否存在,不存在就会创建
#判断如果不是目录,则创建目录
[ ! -d "${BAKUPPATH}/${DATETIME}" ] && mkdir -p "${BAKUPPATH}/${DATETIME}"

#备份数据库+压缩
mysqldump -u${DB_NAME} -p${DB_PWD} --host=${HOST} --databases ${DATABASE} | gzip > ${BAKUPPATH}/${DATETIME}/$DATABASE.sql.gz

#删除前2天的备份文件
find $BAKUPPATH -mtime +2 -type d -exec rm -rf {
    
    } \;

insert image description here
You can modify the above script according to your needs

Next, edit the timed task, we set the script to be executed automatically at 1 am every day

0 1 * * * sh /root/mysql_db_bakup.sh >> /root/mysql_bakup_log/$(date +"\%Y-\%m-\%d").log 2>&1

ok, that's it

Guess you like

Origin blog.csdn.net/qq_42716761/article/details/129591371