清理临时文件的脚本怎么写

wen 实用脚本 1

本文目录导读:

清理临时文件的脚本怎么写

  1. Linux/macOS Bash 脚本
  2. Windows PowerShell 脚本
  3. Python 跨平台脚本
  4. 带用户确认的高级版本
  5. 定时清理脚本(cron job)
  6. 使用说明

Linux/macOS Bash 脚本

#!/bin/bash
# 清理临时文件脚本
echo "开始清理临时文件..."
# 清理 /tmp 下 7 天前的文件
find /tmp -type f -mtime +7 -delete 2>/dev/null
# 清理用户临时目录
rm -rf ~/.cache/* 2>/dev/null
rm -rf ~/.local/share/Trash/* 2>/dev/null
# 清理系统日志
find /var/log -name "*.log" -mtime +30 -delete 2>/dev/null
# 清理软件包缓存
apt-get clean 2>/dev/null  # Debian/Ubuntu
yum clean all 2>/dev/null  # CentOS/RHEL
# 清理 Docker 临时文件
docker system prune -f 2>/dev/null
echo "临时文件清理完成!"

Windows PowerShell 脚本

# 清理临时文件脚本
Write-Host "正在清理临时文件..." -ForegroundColor Green
# 清理 Windows 临时文件夹
Remove-Item "$env:TEMP\*" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item "C:\Windows\Temp\*" -Recurse -Force -ErrorAction SilentlyContinue
# 清理浏览器缓存
Remove-Item "$env:LOCALAPPDATA\Google\Chrome\User Data\*\Cache\*" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item "$env:LOCALAPPDATA\Microsoft\Edge\User Data\*\Cache\*" -Recurse -Force -ErrorAction SilentlyContinue
# 清理回收站
Clear-RecycleBin -Force -ErrorAction SilentlyContinue
# 清理系统错误报告
Remove-Item "C:\ProgramData\Microsoft\Windows\WER\ReportQueue\*" -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "清理完成!" -ForegroundColor Yellow

Python 跨平台脚本

import os
import shutil
import tempfile
import time
from pathlib import Path
def clean_temp_files():
    """清理临时文件"""
    print("开始清理临时文件...")
    # 清理系统临时目录
    temp_dirs = [
        tempfile.gettempdir(),
        os.path.expanduser("~/.cache"),
        "/var/tmp" if os.name == "posix" else os.environ.get("TEMP", ""),
    ]
    # 清理超过 3 天的文件
    threshold = time.time() - (3 * 24 * 3600)
    for temp_dir in temp_dirs:
        if not os.path.exists(temp_dir):
            continue
        try:
            for item in Path(temp_dir).glob("*"):
                try:
                    if item.is_file():
                        if item.stat().st_mtime < threshold:
                            item.unlink()
                            print(f"删除文件: {item}")
                    elif item.is_dir():
                        if item.stat().st_mtime < threshold:
                            shutil.rmtree(item)
                            print(f"删除目录: {item}")
                except Exception as e:
                    print(f"无法删除 {item}: {e}")
        except Exception as e:
            print(f"访问目录失败 {temp_dir}: {e}")
    # 清理日志文件
    if os.name == "posix":
        log_dir = "/var/log"
        if os.path.exists(log_dir):
            for log in Path(log_dir).glob("*.log"):
                try:
                    if log.stat().st_mtime < threshold:
                        log.unlink()
                        print(f"删除日志: {log}")
                except Exception as e:
                    print(f"无法删除日志 {log}: {e}")
    print("清理完成!")
if __name__ == "__main__":
    clean_temp_files()

带用户确认的高级版本

#!/bin/bash
# 显示磁盘使用情况
echo "清理前的磁盘使用情况:"
df -h /tmp /var /home
# 询问用户确认
read -p "确认清理所有临时文件?(y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    # 统计会删除的文件大小
    echo "准备清理的文件大小:"
    du -sh /tmp/* 2>/dev/null | sort -rh | head -20
    # 执行清理
    echo "正在清理..."
    find /tmp -type f -mtime +1 -exec rm -f {} \; 2>/dev/null
    # 清理后的状态
    echo "清理后的磁盘使用情况:"
    df -h /tmp /var /home
else
    echo "操作取消"
    exit 1
fi

定时清理脚本(cron job)

# 保存为 /etc/cron.daily/cleanup-temp
#!/bin/bash
# 每天凌晨 2 点执行
0 2 * * * /usr/local/bin/cleanup.sh
# cleanup.sh 内容
LOG_FILE="/var/log/cleanup.log"
echo "$(date) 开始清理" >> $LOG_FILE
# 保留最近 30 天的日志
find /var/log -name "*.log.*" -mtime +30 -delete
# 清理 /tmp 下超过 7 天的文件
find /tmp -type f -mtime +7 -delete
echo "$(date) 清理完成" >> $LOG_FILE

使用说明

  1. 选择适合的脚本:根据你的操作系统选择对应的脚本
  2. 测试运行:先在非生产环境测试
  3. 调整参数:根据需要修改天数、路径等参数
  4. 添加安全措施:建议清理前先备份重要文件

⚠️ 注意事项

  • 清理前务必确认没有重要数据
  • 某些系统文件可能正在使用中,删除会失败(正常现象)
  • 建议先在测试环境验证效果

需要我帮你针对特定系统或需求调整代码吗?

抱歉,评论功能暂时关闭!