下面从目的、常见清理内容、脚本写法示例、注意事项几个方面,说明如何写一个 Linux cleanup(清理)脚本。
常见清理对象包括:
/tmp, /var/tmp)/var/log)#!/bin/bash
set -euo pipefail
LOG_FILE="/var/log/cleanup.log"
log() {
echo "[$(date '+%F %T')] $*" | tee -a "$LOG_FILE"
}
log "=== Cleanup start ==="
# 清理内容写在这里
log "=== Cleanup done ==="
find /tmp -type f -mtime +7 -delete
find /var/log -type f -name "*.log" -mtime +7 -delete
apt-get clean
apt-get autoremove -y
yum clean all
# 或
dnf clean all
docker system prune -af
apt-get purge -y $(dpkg -l | grep 'linux-image' | awk '{print $2}' | grep -v `uname -r`)
# 每天凌晨 3 点执行
0 3 * * * /root/scripts/cleanup.sh
rm -rffind 测试,确认无误再加 -deletedry-run 思路:find /tmp -mtime +7 -print
#!/bin/bash
set -euo pipefail
log() {
echo "[$(date '+%F %T')] $*"
}
log "Cleanup start"
find /tmp -type f -mtime +7 -delete
find /var/log -type f -name "*.log" -mtime +7 -delete
apt-get clean
docker system prune -af
log "Cleanup finished"
如果你愿意,可以告诉我:
我可以直接帮你写一个可用、安全的 cleanup 脚本。