在 Linux 上“自动化 cleanup 任务”通常分三步:确定要清理什么 → 写好清理脚本 → 用调度器自动执行。下面按常见场景给你一套可落地的做法。
/var/log)/tmp、/var/tmp)~/.cache)/usr/local/bin/cleanup.sh#!/bin/bash
# 清理 /tmp 中 7 天未访问的文件
find /tmp -type f -atime +7 -delete
# 清理日志(保留最近 30 天)
find /var/log -type f -name "*.log" -mtime +30 -delete
# 清理 apt 缓存(Debian/Ubuntu)
apt-get clean
# 清理 yum 缓存(CentOS/RHEL)
# yum clean all
# 删除旧内核(Ubuntu 示例)
# apt-get autoremove --purge -y
# Docker 清理(可选)
# docker system prune -af
赋予执行权限:
chmod +x /usr/local/bin/cleanup.sh
crontab -e
添加:
0 2 * * * /usr/local/bin/cleanup.sh >> /var/log/cleanup.log 2>&1
/etc/systemd/system/cleanup.service
[Unit]
Description=Linux Cleanup Task
[Service]
Type=oneshot
ExecStart=/usr/local/bin/cleanup.sh
/etc/systemd/system/cleanup.timer
[Unit]
Description=Run cleanup daily
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
systemctl enable --now cleanup.timer
查看状态:
systemctl list-timers
logrotate 管理日志(不要手动删)echo 模拟:find /tmp -type f -atime +7 -print
nice / ionice 降低清理对系统影响可以告诉我:
我可以给你更精确的自动化方案。