linux数据库和文件夹定时备份删除

linux数据库和文件夹定时备份删除

写shell脚本 作为定时执行的备份mysql数据库文件和文件夹文件

1.mysql 数据导出和打包备份 mysqlback.sh

#!/bin/sh 
# File: /root/mysqlback.sh
# Database info 
DB_NAME="test" 
DB_USER="username" 
DB_PASS="password"

# Others vars 
BIN_DIR="/usr/local/mysql/bin" 
BCK_DIR="/data/backup/mysql" 
DATE=`date +%Y%m%d_%H:%M:%S`

# TODO 
$BIN_DIR/mysqldump --opt -u$DB_USER -p$DB_PASS $DB_NAME | gzip > $BCK_DIR/$DATE.db.gz

2.文件夹备份和删除之前备份脚本 dirback.sh


#!/bin/sh 
# File:/root/dirback.sh
#备份文件 
#定义今天的时间作为文件的名
now =`date %Y%m%d_%H_%M_%S`
#文件要备份到的位置
backpath=/data/mybackup/
#要备份的文件路径
respath =/root/tomcat/app
tar -zcvf /$backpath/${now}.bak.tar.gz $respath

#删除之前备份的文件
if [ `whoami` != 'root' ];then
        echo "Must be root run this scripts!!" >> /var/log/backup/messages
        exit
fi
#这里定义删除一天之前的时间,也就是备份完了删除上一天备份的数据
ago=`date -d "-1 day" +%Y%m%d`
if [ ! -d $backpath ];then
        echo "This path [${$backpath}] not exist, please check." >> /var/log/backup/messages
        exit
fi
for i in `ls $backpath`
do
# Get datestamp and check it. For example: 20160526_11_00_00.bak.tar.gz
        datestamp=`echo $i | awk -F'_' '{print $1}'`
        check=`echo "$datestamp" | grep "^[0-9]\{8\}$"`
        if [ "$check" != '' ];then
                # Remove old files.
                if [ "$datestamp" -lt "$ago" ];then
                        /bin/rm -rf $backpath/$i
                fi
        fi
done

3.执行命令授权
chmod 777 /root/mysqlback.sh
chmod 777 /root/dirback.sh
corntab -e
0 5 * * * sh /root/mysqlback.sh
1 5 * * * sh /root/dirback.sh

你可能感兴趣的:(shell,备份)