在 Linux 系统上做“自动 cleanup(自动清理)”通常有几种常见场景和做法。下面按使用频率从高到低给你一个实用指南。
# 每天凌晨 3 点清理 /tmp 中 7 天前的文件
0 3 * * * find /tmp -type f -mtime +7 -delete
# 每周清理 /var/log 下超过 30 天的 .log
0 4 * * 0 find /var/log -name "*.log" -mtime +30 -delete
0 2 * * * find ~/.cache -type f -mtime +14 -delete
编辑定时任务:
crontab -e
systemd-tmpfiles(现代 Linux 推荐)配置文件在:
/etc/tmpfiles.d/
示例(清理 /tmp 中 10 天前的文件):
# /etc/tmpfiles.d/cleanup.conf
d /tmp 1777 root root 10d
手动执行:
systemd-tmpfiles --clean
# 每天清理无用容器、镜像、卷
0 1 * * * docker system prune -af
更安全的:
docker image prune -af --filter "until=72h"
apt-get clean
apt-get autoremove -y
yum clean all
可写入 cron:
0 5 * * 0 apt-get clean && apt-get autoremove -y
系统已默认启用:
/etc/logrotate.conf
/etc/logrotate.d/
示例:
/var/log/myapp.log {
daily
rotate 7
compress
missingok
notifempty
}
#!/bin/bash
# /usr/local/bin/cleanup.sh
find /tmp -mtime +7 -delete
docker system prune -af
apt-get clean
chmod +x /usr/local/bin/cleanup.sh
cron:
0 3 * * * /usr/local/bin/cleanup.sh
rm -rf /find ... -print 测试prune -a如果你能告诉我:
我可以给你一套精准的自动清理方案。