可以的,Linux 下的 cleanup(清理)完全可以自动化。常见做法从“简单脚本 + 定时任务”到“系统级自动清理工具”都有。下面按从易到难、从手动到自动给你一个清晰地图。
例如清理日志和临时文件:
#!/bin/bash
# cleanup.sh
# 删除 /tmp 下 7 天未访问的文件
find /tmp -type f -atime +7 -delete
# 清理系统日志
journalctl --vacuum-time=7d
# 清理 apt 缓存(Debian/Ubuntu)
apt-get clean
# 清理 yum 缓存(CentOS/RHEL)
# yum clean all
chmod +x cleanup.sh
crontab -e
每天凌晨 3 点执行:
0 3 * * * /path/to/cleanup.sh
✅ 优点:灵活、可控
❌ 缺点:需要自己写逻辑
systemd-tmpfiles(现代 Linux 推荐)很多发行版已经自动在用。
配置文件:
/etc/tmpfiles.d/
示例(清理 /tmp 中 10 天前的文件):
# /etc/tmpfiles.d/cleanup.conf
d /tmp 1777 root root 10d
手动测试:
systemd-tmpfiles --clean
✅ 系统级、安全
✅ 很多服务已在用
logrotate(专清日志)自动轮转 + 压缩 + 删除旧日志。
配置文件:
/etc/logrotate.conf
/etc/logrotate.d/
示例:
/var/log/myapp/*.log {
daily
rotate 7
compress
missingok
notifempty
}
✅ 日志清理标准方案
apt-get autoremove
apt-get autoclean
可加入 cron:
0 4 * * 0 apt-get autoremove -y
yum autoremove
如果你是 Docker 用户:
docker system prune -af
定时任务:
0 2 * * * docker system prune -af
✅ 普通服务器:
logrotate + systemd-tmpfiles + 每周 cron 脚本✅ 生产服务器:
如果你愿意,可以告诉我:
我可以直接帮你写一套可落地的自动化 cleanup 方案。