Linux删除日志的脚本,linux定时删除历史日志文件实现方式--shell脚本

1、tools目录文件结构

[root@www tools]# tree tools/

tools/

├── bin

│ ├── del_history_files

└── etc

├── del_history_files.cfg

2 directories, 2 files

2、删除历史文件脚本 del_history_files

[root@www tools]# more tools/bin/del_history_files

#!/bin/sh

# 删除指定目录下,文件时间早于指定时间节点的文件,时间粒度:小时

# 配置文件格式 : 需清理的目录=小时数

#

#

# define restricted path

PATH="/bin:/usr/bin:/sbin:/usr/sbin"

# adirname - return absolute dirname of given file

adirname() { odir=`pwd`; cd `dirname $1`; pwd; cd "${odir}"; }

# ---------

# constants

# ---------

MYNAM=`basename "$0"`

MYDIR=`adirname "$0"`

MYCFG="${MYDIR}/../etc/${MYNAM}.cfg"

MYTMP="${MYDIR}/../tmp"

MYLCK="${MYTMP}/${MYNAM}.lock"

# perform some locking (as good as it gets in a shell)

[ -s "${MYLCK}" ] && kill -0 `cat "${MYLCK}"` 2>/dev/null &&

die "${MYNAM}: already running!"

echo "$$" > "${MYLCK}"

PATHS=(`cat ${MYCFG}`)

for PP in ${PATHS[@]}

do

APP_PATH=`echo ${PP} | awk -F'=' '{print $1}'`

N=`echo ${PP} | awk -F'=' '{print $2}'`

if [ -d ${APP_PATH} ] ; then

T=`/bin/date --date "${N} hours ago" "+%Y%m%d%H%M"`

TMP_FILE="/tmp/`echo ${PP} | md5sum | awk '{print $1}'`"

touch -t ${T} ${TMP_FILE}

find ${APP_PATH} ! -newer ${TMP_FILE} -type f -print0 | xargs -0 -n 100 rm -rf

find ${APP_PATH} -type d -empty -print0 | xargs -0 -n 100 rm -rf &> /dev/null

fi

done

rm -rf ${MYLCK}

3、删除历史文件脚本的配置文件 del_history_files.cfg

[root@www tools]# more tools/etc/del_history_files.cfg

#需清理的目录=小时数

/home/logs/nginx=720

/home/logs/varnish=720

4、crontab 执行即可

[root@www tools]# more /etc/crontab

SHELL=/bin/bash

PATH=/sbin:/bin:/usr/sbin:/usr/bin

MAILTO=root

HOME=/

#clear old logs

00 6 * * * root /home/tools/bin/del_history_files

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值