温馨提示×

怎样写linux cleanup脚本

小樊
38
2026-09-29 13:26:43
栏目: 智能运维

下面从目的、常见清理内容、脚本写法示例、注意事项几个方面,说明如何写一个 Linux cleanup(清理)脚本。


一、先明确:cleanup 脚本通常干什么?

常见清理对象包括:

  • 临时文件(/tmp, /var/tmp)
  • 日志文件(/var/log)
  • 缓存(apt/yum/dnf、pip、npm)
  • 旧内核
  • 用户或项目产生的临时目录
  • 容器/镜像(Docker)
  • 自定义业务垃圾文件

二、基本脚本结构(推荐)

#!/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 ==="

三、常见清理示例

1. 清理 /tmp 下 7 天前的文件

find /tmp -type f -mtime +7 -delete

2. 清理日志(保留最近 3 个或 7 天)

find /var/log -type f -name "*.log" -mtime +7 -delete

3. 清理 apt 缓存(Debian/Ubuntu)

apt-get clean
apt-get autoremove -y

4. 清理 yum/dnf 缓存(CentOS/RHEL)

yum clean all
# 或
dnf clean all

5. 清理 Docker(谨慎)

docker system prune -af

6. 清理旧内核(Ubuntu 示例)

apt-get purge -y $(dpkg -l | grep 'linux-image' | awk '{print $2}' | grep -v `uname -r`)

四、定时执行(cron)

# 每天凌晨 3 点执行
0 3 * * * /root/scripts/cleanup.sh

五、重要注意事项(很重要)

  1. 不要盲目 rm -rf
  2. 清理前先 find 测试,确认无误再加 -delete
  3. 生产环境务必加日志
  4. 对正在使用的文件要小心(如数据库日志)
  5. 可用 dry-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"

如果你愿意,可以告诉我:

  • 你是 个人服务器 / 生产环境 / 容器环境
  • 想清理 哪类东西
  • 用 哪个 Linux 发行版

我可以直接帮你写一个可用、安全的 cleanup 脚本。

0 踩