shell 脚本 — 定时备份文件及删除文件

      shell 脚本 — 定时备份文件及删除文件已关闭评论

1. 创建备份脚本

$ mkdir /usr/local/script
$ vim /usr/local/script/back_file.sh
#!/bin/bash
# author:        jack.zang
# date:          2019-11-20
# description:   backup files
##################################################
LogFile=/data/backup/log/`date +"%Y%m"`.log
DATE=`date +"%Y%m%d"`
# 指定要备份的文件,eg:/var/log/slapd.log
BackFileList=/data/backup/back-file-list.txt
BackDir=/data/backup
# 保持多少天备份
RetainDay=30
##################################################

mkdir -p ${LogFile%/*} $BackDir

back_file() {
   echo "[Backup] start at $(date +"%Y-%m-%d %H:%M:%S")" >> $LogFile
   echo "--------------------------------------------------" >> $LogFile
   BACK_FILE_LIST=`cat $BackFileList`

   for BACK_FILE in $BACK_FILE_LIST; do
       FILE=${BACK_FILE##*/}
       tar -zcPvf $BackDir/${FILE}_$(date +%Y%m%d).tar.gz $BACK_FILE > /dev/null
       echo "Backup $BACK_FILE done into $BackDir" >> $LogFile
   done
   echo "backup end at $(date +"%Y-%m-%d %H:%M:%S")" >> $LogFile
}

del_old_file() {
   find $BackDir -mtime +${RetainDay} -name "*.tar.gz" -exec rm -rf {} \;
}

back_file
del_old_file

2. 设置定时任务

//创建需要备份的文件

$ mkdir /data/backup
$ vi /data/backup/back-file-list.txt
/var/log/messages
/var/log/secure

//创建定时任务,每隔两天备份一次,每次凌晨3点备份

$ chmod +x /usr/local/script/back_file.sh
$ crontab -e
0 3  */2  *  * /usr/local/script/back_file.sh