测试工作经常需要Jenkins构建,有时提示空间不足,我们需要定期去清理日志,部分日志文件是不能直接删除,如果服务器部署多个项目,每个项目都有很多日志,甚至个别文件很大,此时手动打开文件,人为去删除效率很慢.故需要借助shell脚本去定期清理日志内容. 详细操作步骤如下:
步骤1: 创建文件
touch /testlog/del-2-days-ago-log.sh
步骤2: 赋予权限

步骤3:shell文件中添加脚本
vim /testlog/del-2-days-ago-log.sh

步骤4:输入i 进入编辑模式
步骤5: 输入命令

#/bin/bash
for i in `find /testlog -name "*.log"`
do
cat /dev/null > $i
done
命令延伸知识
删除/opt目录下所有的日志文件
find /opt -name *.log.* | xargs rm -rf
查看/opt目录下,所有日志文件及大小
find /opt -name *.log | xargs du -sh
查找目录下的.log后缀的文件,并清空文件内容(这里不是删除文件)
find /opt -name *.log -exec cp /dev/null {} \;
步骤6: ESC 退出编辑模式
步骤7: :wq!保存离开
步骤8: 查看定时任务是否安装
systemctl status crond

查看crontab是否已安装
rpm -qa | grep crontab

步骤9: crontab -e

步骤10: 输入定时脚本
定时5分钟执行一次
*/5 * * * * /testlog/del-2-days-ago-log.sh
步骤11: :wq!保存定时任务 提示添加成功
crontab: installing new crontab
注意:用crontab -e 编辑的定时任务三分钟之内是不会执行的,所以在测试的时候,至少时间后推三分钟!
步骤12: 查看定时任务日志是否执行
tail -f /var/log/cron

单个定时清理日志内容保留文件

批量清理日志内容保留文件

步骤13: 查看已经创建的计划任务
crontab -l

步骤14: 删除定时任务
- 进入计划服务配置界面
crontab -e
- 删除计划任务
dd
- 保存并退出
:wq!
- 再次查看
crontab -l

网友评论