在 CentOS 中,“cleanup(清理)”一般通过 定时任务(cron) 来实现。下面从 基础用法 → 常见清理示例 → 实战配置 给你讲清楚。
systemctl status crond
systemctl start crond
systemctl enable crond
crontab -e
* * * * * command
分 时 日 月 周
示例:
0 3 * * * → 每天凌晨 3 点*/30 * * * * → 每 30 分钟0 0 * * 0 → 每周日 0 点0 2 * * * yum clean all
0 3 * * * find /tmp -type f -mtime +7 -delete
0 4 * * * find /var/log -type f -name "*.log" -mtime +30 -delete
⚠️ 注意:直接用 -delete 有风险,建议先测试:
find /var/log -type f -name "*.log" -mtime +30
vim /root/cleanup.sh
内容示例:
#!/bin/bash
# cleanup script
# yum
yum clean all
# tmp
find /tmp -type f -mtime +7 -delete
# logs
find /var/log -type f -name "*.log" -mtime +30 -delete
# docker(如有)
docker system prune -f
chmod +x /root/cleanup.sh
crontab -e
0 3 * * * /root/cleanup.sh >> /var/log/cleanup.log 2>&1
路径:
/etc/cron.daily/
/etc/cron.weekly/
示例:
cp /root/cleanup.sh /etc/cron.daily/cleanup
chmod +x /etc/cron.daily/cleanup
系统会自动按天执行。
grep CRON /var/log/cron
-print 测试如果你愿意,可以告诉我:
我可以给你精确的 cleanup 定时任务配置。