本文目录导读:

要用脚本定期清理旧文件,推荐使用 Shell 脚本(Linux/macOS)或 PowerShell 脚本(Windows)结合系统的定时任务(cron / 任务计划程序),以下是具体实现方法:
Linux/macOS 环境(Shell + cron)
编写清理脚本
创建一个脚本文件 cleanup.sh如下:
#!/bin/bash
# 清理指定目录下30天前的 .log 文件
DIR="/var/log/myapp"
DAYS=30
# 查找并删除符合条件的文件
find "$DIR" -type f -name "*.log" -mtime +$DAYS -exec rm -f {} \;
# 可选的日志记录
echo "$(date) - 清理完成" >> /var/log/cleanup.log
参数说明:
-mtime +$DAYS:修改时间在 $DAYS 天前的文件(+表示大于)-exec rm -f {}:对找到的文件执行删除操作- 如要删除空目录,可添加
-type d和-empty
增加安全性:
# 使用 -delete 替代 -exec rm,更安全 find "$DIR" -type f -name "*.log" -mtime +$DAYS -delete
赋予执行权限
chmod +x cleanup.sh
设置 cron 定期任务
编辑 cron 表:
crontab -e
添加如下一行(每天凌晨 3 点执行):
0 3 * * * /path/to/cleanup.sh
cron 时间格式:
分 时 日 月 周
0 3 * * *= 每天3:000 3 * * 0= 每周日凌晨3:000 3 1 * *= 每月1号3:00
Windows 环境(PowerShell + 任务计划程序)
编写 PowerShel 清理脚本
创建 Cleanup.ps1 文件:
# 配置参数
$TargetFolder = "C:\Logs"
$DaysOld = 30
$LogFile = "C:\Scripts\cleanup.log"
# 获取旧文件并删除
Get-ChildItem -Path $TargetFolder -Recurse -Include *.log |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$DaysOld) } |
Remove-Item -Force
# 记录日志
"$(Get-Date) - 清理完成" | Out-File -Append $LogFile
如要删除空目录:
# 删除30天前未被修改的空目录
Get-ChildItem -Path $TargetFolder -Directory |
Where-Object { (Get-ChildItem $_.FullName -Recurse -File).Count -eq 0 -and $_.LastWriteTime -lt (Get-Date).AddDays(-$DaysOld) } |
Remove-Item -Force
允许执行脚本(若未启用)
以管理员身份运行 PowerShell:
Set-ExecutionPolicy RemoteSigned
创建定时任务
- 打开 任务计划程序(运行
taskschd.msc) - 点击“创建任务”
- 设置触发器(如每天凌晨3点)
- 设置操作:
- 程序/脚本:
powershell.exe - 添加参数:
-File "C:\Scripts\Cleanup.ps1" -ExecutionPolicy Bypass
- 程序/脚本:
进阶功能与注意事项
✅ 保留最近N个文件(不按时间)
# 保留最近5个日志文件,删除更旧的 ls -1t /var/log/*.log | tail -n +6 | xargs rm -f
✅ 只删除特定大小的文件
# 删除30天前且大于100MB的文件 find /data -type f -size +100M -mtime +30 -delete
✅ 发送通知(失败时)
find /path -delete || echo "清理失败" | mail -s "Cleanup Error" admin@example.com
⚠️ 重要安全建议
- 先测试再上线:用
-print替代-delete先查看哪些文件会被删除 - 路径不要写错:尤其不要用
rm -rf /或缺少 - 考虑使用回收站:Linux可用
trash-cli,Windows可用 PowerShellRecycle模块 - 记录日志:方便排查异常删除情况
不同场景示例
| 场景 | 推荐脚本方式 |
|---|---|
| 删除7天前临时文件 | Linux: find /tmp -type f -mtime +7 -delete |
| 删除2周前备份文件 | Windows: Get-ChildItem *.bak \| Where LastWriteTime -lt (Get-Date).AddDays(-14) \| Remove-Item |
| 删除30天前日志,保留最新20个 | 结合 sort 和 head/tail 逻辑 |
| 跨平台统一管理 | 使用 Python 脚本 + schedule 库 |
定好规则、备好日志、先模拟测试,就能安全地让定期清理自动运行了。