#!/bin/bash
##############################################################
#***#***功能:
#***备份日志目录的N天前的日志文件成压缩文件,并移动到指定的统一备份目录
#***#***参数:
#*** $1:N天之前 ,默认:30#*** $2:要备份的日志文件查询格式,默认:*.log
#*** $3:要备份的日志所在绝对路径,默认:/var/log
#*** $4:备份文件夹名称,默认:backup-log_日期,示例:backup-log_2020-09-04-03-11-42#*** $5:压缩后的本分文件夹最终存储绝对路径,默认:/data/backup-log
#***##############################################################
#1.进入目标目录
# cd
#2.找出指定路路下的N天前的指定后缀的的所有普通文件
#find ./ -type f -mtime +30 -name "*.log"#3.需要备份的文件存在,且当前目录下不存在则创建备份文件夹
# dirName= date "+%Y-%m-%d-%H-%M-%S"#mkdirdirName
#4.移动目标文件到备份目录
#mv#5.备份成功则压缩备份目录,并删除本分目录
#
#6.移动备份压缩文件到指定的全局备份文件夹
# 帮助functionhelp(){awk '/^\#\*{3}/ { print $2 }' $0}if [[ "$1" == "-h" ]];thenhelp
exitfi######################## 可修改参数 ###########################
# 备份N天前修改的文件
nDays=$1# 指定的文件后缀
suffix=$2# 操作目标日志目录
targetLogPath=$3# 备份文件夹名称
tarTargetDirName=$4# 统一压缩日志文件备份目录
tarGzLogFilesPath=$5# 参数检测
##*************************** $1 *******************************#if [[ -z $nDays || $nDays -lt 1 ]];thennDays=30
fi
echo -e "备份N天之前的日志文件:$nDays 天之前"##*************************** $2 *******************************#if [ -z $suffix ];thensuffix="*.log"
fi
echo -e "备份的日志文件后缀为:$suffix"##*************************** $3 *******************************#if [ -z $targetLogPath ];thentargetLogPath="/var/log"
fi
echo -e "要备份的日志目录为:$targetLogPath"##*************************** $4 *******************************#if [ -z $tarTargetDirName ];thentarTargetDirName="backup-log_"
fitarTargetDirName=$tarTargetDirName`date "+%Y-%m-%d-%H-%M-%S"`echo -e "备份日志存储目录为:$tarTargetDirName"##*************************** $5 *******************************#if [ -z $tarGzLogFilesPath ];thentarGzLogFilesPath="/data/backup-log"
fi
echo -e "压缩后的备份日志存储目录为:$tarGzLogFilesPath"
echo -e "------------------------------------------------------"###############################################################
#1进入目标目录if [ ! -d $targetLogPath ];then
echo $targetLogPath"目录不存在"exitficd $targetLogPath
#2找出指定路路下的N天前的指定后缀的的所有普通文件
findTargetFiles=`find $targetLogPath -type f -mtime +$nDays -name "$suffix"`echo -e "需要备份的文件:"
echo$findTargetFiles
#3.1检测文件是否存在
len=${#findTargetFiles}if [ $len -eq 0 ];then
echo "不存在需要备份的日志文件"exitfi#3.2创建备份文件存储文件夹
# 创建备份文件夹functioncreateDirIfNotExist(){if [ ! -d $1 ];then
mkdir $1
else
echo $1"已存在"
fi}
tarTargetDirPath=$tarTargetDirName
createDirIfNotExist $tarTargetDirPath
#4移动目标文件到备份目录mv -b $findTargetFiles $tarTargetDirPathif [ $? -ne 0 ];then
echo "移动日志文件到当前备份目录失败"exitfi#5.1备份成功则压缩备份目录
backGzFile=$tarTargetDirPath".tar.gz"
tar -zcvf $backGzFile $tarTargetDirPath
#5.2压缩成功则删除当前备份目录if [ $? -ne 0 ];then
echo "备份失败"exitelse
rm -rf $tarTargetDirPathecho "备份成功"
fi#6移动备份压缩文件到指定的全局备份文件夹
createDirIfNotExist $tarGzLogFilesPathmv$backGzFile $tarGzLogFilesPathif [ $? -ne 0 ];then
echo "压缩日志文件备份失败"
else
echo "压缩日志文件备份成功"
fiexit