SHELL脚本:定期清理日志文件

1、脚本实现的功能

定期清理指定的日志目录或者文件

2、脚本使用说明

#./log_clean.sh 日志目录/文件 保留天数

脚本会对大于保留天数的的日志目录或者文件进行删除或者重定向清理,因为这个脚本编写的目的非常简单,就是清理日志文件,所以没有备份功能,把脚本添加到crontab既可实现定期清理功能,如果有多个目录或者文件,就添加多个条目。

3、脚本内容

#!/bin/bash

clean_file=$1
save_time=$2

today=`date +"%F_%T"`
Now_time=`date +%s`

Logfile=/tmp/log_clean.log

if [ -d ${clean_file} ]
then
    cd "${clean_file}"
    echo "${today} ${clean_file} ${save_time} days ago are to be deleted ....." >> ${Logfile}
    find . -mtime +${save_time} -type f -print0|xargs -0 rm -f
elif[ -f ${clean_file} ]
then
    file_modtime=`stat -c %Y ${clean_file}`
    if [ $[${Now_time}-${file_modtime}] -gt $[${save_time}*86400] ];then
        > ${clean_file}
        echo "${today} ${clean_file} ${save_time} days ago are to be deleted ....." >> ${Logfile}
    fi
fi

Jimmy's Blog ,版权所有丨如未注明,均为原创丨本网站采用BY-NC-SA协议进行授权,转载请注明转自:https://www.xjimmy.com/shell_log_clean.html

Leave a Comment