Shell: 定期存档日志文件

简介

对于日志的分割删除我们一般会使用logratate,但对于项目较多的情况下,会让开发直接将日志分割写在代码里面,对于分割后过期的日志定期删除就很有必要,不然膨胀的日志会占满你的磁盘,将多余的日志删除或挪到其他地方就是这个脚本的功能,如果有用请拿去自做修改,不谢。

效果截图

需要处理日志目录

img-w500

处理后存放日志文件目录

img-w500

脚本内容dellog.sh

#!/bin/bash
# William Guozi
# https://www.cnblogs.com/William-Guozi, williamguozi.github.io
# You are free to modify and distribute this code,
# so long as you keep my name and URL in it.

#指定本脚本日志文件
logfile=/data/scripts/dellog.log
#要处理的日志文件目录
logdir=$1

#函数体,对目录内所有文件进行遍历
foreachd(){
        for file in $1/*
        do
                if [ -d $file ];
                then
			#输入遍历过程的日志
                        echo `date`: "$file is dir" >> $logfile
			#如果是目录,调用该函数遍历
                        foreachd $file
		#如果是文件,将符合条件的做相应处理
                elif [ -f $file ];
                then
			#输入遍历过程的日志
                        echo `date`: "$file is file" >> $logfile
			#取出文件名
			baseName=`basename $file`
			#取文件上级目录做日志类型区分
			nameType=`echo $file | awk -F/ '{print $(NF-1)}'`
			#将文件进行筛选,将修改时间为今天以前名字中还有.的文件移动到/logs下,并重命名
                        find $file -mtime +0 -name "*.*" | xargs -I {} mv {} /logs/$baseName.$nameType
                fi
        done
}

#判断参数是否为空,为空,显示帮助,不为空则调用函数
if [[ "x$logdir" == 'x' ]];
then
        echo "Useage: bash dellog.sh dir.  eg: bash dellog.sh /data/logs"
else
        foreachd "$logdir"
fi

定时任务crontab

crontab -l
#delete log file
HOME=/data/scripts/
00 1 * * * /bin/bash /data/scripts/dellog.sh /data/logs

参考

https://blog.csdn.net/neil4/article/details/68945642

原文地址:https://www.cnblogs.com/William-Guozi/p/Shell_function.html