阿里云服务器mysql定时自动备份脚本(ubuntu 16.04)

脚本 mysql_backup.sh
脚本路径:/home/ldh/mysql_backup

#!/bin/bash

# 备份文件存放地址(根据实际情况填写),不要跟 .sh 脚本放在同一目录,
# 不然下面删除过期数据会把脚本删除,这里不想修改删除指令,所以通过不放在一起避免该情况
backup_location=/home/ldh/mysql_backup/backup_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 3306|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

# 备份指定数据库中数据(此处假设数据库是essp_org)
mysqldump --defaults-extra-file=/etc/mysql/debian.cnf --single-transaction --routines --flush-logs --databases essp_org > $backup_dir/essp_org-$backup_time.sql
flag=`echo $?` 
if [ $flag == "0" ];then
        echo "database essp_org success backup to $backup_dir/essp_org-$backup_time.sql"
else
        echo "database essp_org 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

然后终端输入:contab -e 设置定时指令,然后新增以下内容

0 3 * * * cd /home/ldh/mysql_backup;bash essp_backup.sh >> log.txt

开头的 0 3 代表每天凌晨 3:00 定时执行。

你可能感兴趣的:(阿里云服务器mysql定时自动备份脚本(ubuntu 16.04))