在 Ubuntu 上做“自动化清理”通常分几个层次:一次性手动清理 → 定时任务(cron/systemd) → 自动化脚本/工具。下面按实用程度给你一套可落地的方案。
sudo apt autoremove --purge -y
sudo apt autoclean
sudo journalctl --vacuum-time=7d
rm -rf ~/.cache/*
rm -rf ~/.local/share/Trash/*
sudo nano /usr/local/bin/ubuntu-cleanup.sh
内容示例:
#!/bin/bash
set -e
echo "==> Cleaning apt"
apt autoremove --purge -y
apt autoclean
echo "==> Cleaning journal"
journalctl --vacuum-time=7d
echo "==> Cleaning user cache"
rm -rf /home/*/.cache/*
echo "==> Done"
赋予执行权限:
sudo chmod +x /usr/local/bin/ubuntu-cleanup.sh
sudo crontab -e
添加:
0 3 * * 0 /usr/local/bin/ubuntu-cleanup.sh >> /var/log/cleanup.log 2>&1
sudo nano /etc/systemd/system/cleanup.service
[Unit]
Description=Ubuntu Cleanup
[Service]
Type=oneshot
ExecStart=/usr/local/bin/ubuntu-cleanup.sh
sudo nano /etc/systemd/system/cleanup.timer
[Unit]
Description=Weekly Cleanup
[Timer]
OnCalendar=weekly
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl enable --now cleanup.timer
查看状态:
systemctl list-timers
sudo apt install bleachbit
可设置自动清理策略(GUI)
sudo apt install ncdu
ncdu /
/var/log 全部docker system prune -f
如果你愿意,可以告诉我:
我可以直接帮你生成完整可用脚本 + 定时器配置。