Linux 定时删除日志
导语
项目中会生成各种各样的日志,随着时间的推移,日志也是越来越多。超过一定时间的日志就没有了参考的价值,也会占用空间,所以一般的项目都会删除日志。本篇文章的需求是删除 7 天之前的日志,大致分为两步,一是删除日志的命令,二是设置定时任务。
删除指定时间的日志
首先是查找所有 7 天前的日志,使用 find
查找的时候加上 -mtime
参数,其含义为 查找在指定时间曾被更改过的文件或目录,单位以24小时计算。实例为 find you/path -mtime +7 -name '*.log'
,如下

查找完成了,接下来是删除。在上面语句的基础上,加上 -exec
参数可以实现删除,参数含义为 假设find指令的回传值为True,就执行该指令。所以完整的语句为 find you/path -mtime +7 -name '*.log' -exec rm -rf {} \;
。实际执行下,删除 16 天之前的日志,不然下面没办法演示了

16 天之前只有一条日志,执行后再次查找不存在,说明删除成功。
设置定时任务
最后将命令添加定时任务。关于 crontab
命令以及执行时间的设定,可以查看下方的参考资料。
添加之前先来看下 14 天之前的日志

有一条日志。编辑定时任务,执行 crontab -e
将删除日志命令追加到末尾 */1 * * * * find you/path -mtime +14 -name '*.log' -exec rm -rf {} \;
,设定为每分钟执行一次。稍等一分钟,再来查看 14 天之前的日志

可以看到在添加定时任务之后,没有手动删除,日志已经被自动删除了。当然不需要每分钟来执行一次,将时间设定为每天 1 点的时间,最终定时任务以及删除日志命令如下
0 1 * * * find you/path -mtime +7 -name '*.log' -exec rm -rf {} \;
