一、需求背景
因此次项目的生产环境中部署了多套系统,每天会产生大量的日志(数百GB的量),侵占了服务器宝贵的存储资源空间。为了有效缓解服务器存储压力,考虑通过Linux的Shell脚本结合crontab定时每周一对上周7天的日志打包压缩,并删除原被打包的日志文件,以腾出更多可利用的存储资源空间。
对于初次接触Shell脚本的同学,建议先花几个小时时间学习一下Shell。附Shell教程链接如下:
http://www.runoob.com/linux/linux-shell-process-control.html
二、Shell脚本
进入Linux终端,键入vim timePackLogs.sh(脚本名称)创建脚本并编辑如下脚本代码:
#!/bin/bash
#author:haw2106
#date:20181213
#department:xxxx
#email:xxxx@xxxx.com
#if you have any questions, please contact the email!
echo `date '+%Y-%m-%d %H:%M:%S'`" 打包程序执行开始!";
echo "开始打包从7天前截止昨天的日志(如本周日打包上周日到上周六的日志)!";
#筛选打包日志文件的起始日期
sevenDaysAgoDate=`date -d "7 days ago" +%Y-%m-%d`
#筛选打包日志文件的截止日期(此处为获取当前日期)
currentDate=`date +%Y-%m-%d`
#起始日期时间戳(作为日期范围对比使用)
sevenTimeStamp=`date -d "$sevenDaysAgoDate" +%s`
#截至日期时间戳
currentTimeStamp=`date -d "$currentDate" +%s`
index=0
#日志读取路径
filePath="/home/weblogic/logs1"
#获取该路径下所有日志文件
fileList=`ls $filePath -1 -c`
#遍历所有日志文件
for fileName in $fileList
do
#将日志文件名及后缀与正则表达式做对比返回yyyy-mm-dd格式的日期值(如2018-09-10)
fileDate=$( expr "$fileName" : '.*[0−9]{4}\-[0−9]{2}\-[0−9]{2}[0−9]{4}\-[0−9]{2}\-[0−9]{2}.*.*' )
#将日期转换为时间戳
fileDateTimeStamp=`date -d "$fileDate" +%s`
#当时间戳值不为空且大于等于起始日期小于当前日期,那么获取该日志文件
if [ "$fileDateTimeStamp" != "" ] && [ $fileDateTimeStamp -ge $sevenTimeStamp ] && [ $fileDateTimeStamp -lt $currentTimeStamp ]
then
fileList[$index]="$filePath/$fileName"
else
fileList[$index]=""
fi
(( index ++ ))
done
#获取所有在日期范围内的日志文件, @代表所有
meetConFiles=${fileList[@]}
#符合条件的日志文件数大于0就打包压缩
if [ "${#meetConFiles}" -gt 0 ]
then
tar -zcvf $currentDate.tar.gz $meetConFiles
else
echo "Not found the meet condition's files!"
exit 0
fi
echo "$currentDate.tar.gz create completion, Now begin to delete old files."
#删除已被打包压缩的日志文件
rm -fr $meetConFiles
echo "done."
exit 0
三、配置