小知识:Linux使用shell脚本定时删除历史日志文件

1、tools目录文件结构

?
1
2
3
4
5
6
7
8
9
[root@www tools]# tree tools/
tools/
├── bin
│  ├── del_history_files
└── etc
├── del_history_files.cfg
2 directories, 2 files

2、删除历史文件脚本 del_history_files

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
[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

?
1
2
3
4
[root@www tools]# more tools/etc/del_history_files.cfg
#需清理的目录=小时数
/home/logs/nginx=720
/home/logs/varnish=720

4、crontab 执行即可

?
1
2
3
4
5
6
7
[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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/xzlive/p/12928905.html

声明: 猿站网有关资源均来自网络搜集与网友提供,任何涉及商业盈利目的的均不得使用,否则产生的一切后果将由您自己承担! 本平台资源仅供个人学习交流、测试使用 所有内容请在下载后24小时内删除,制止非法恶意传播,不对任何下载或转载者造成的危害负任何法律责任!也请大家支持、购置正版! 。本站一律禁止以任何方式发布或转载任何违法的相关信息访客发现请向站长举报,会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。本网站的资源部分来源于网络,如有侵权烦请发送邮件至:2697268773@qq.com进行处理。
建站知识

小知识:Linux Makefile与Shell的问题

2023-5-7 8:25:46

建站知识

小知识:nginx配置ssl双向验证的方法

2023-5-7 23:55:16

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索