Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 定時清理過期文件:find + crontab 自動化運維實戰

編輯:關於 Linux

服務器運行久了,日誌、臨時文件堆積佔用磁盤空間。本文教你用 find 命令精準定位過期文件,結合 crontab 實現全自動定時清理。

核心命令解析

find /var/www/ -type f -mtime +30 -exec rm -f '{} \;
參數含義
/var/www/掃描目標目錄
-type f僅匹配普通文件(排除目錄、鏈接等)
-mtime +30修改時間超過 30 天(+n 表示 n*24 小時前)
-exec rm -f '{} \;執行刪除,{} 佔位符代表匹配文件,\; 結束標記

定時任務配置

crontab -e
# 每天凌晨 1:30 執行清理
30 1 * * * find /var/www/ -type f -mtime +30 -exec rm -f '{} \;

進階用法

按文件大小清理

# 刪除超過 100MB 的舊日誌
find /var/log/ -type f -name "*.log" -size +100M -mtime +7 -exec rm -f '{} \;

安全模式:先列出再刪除

# 添加 -print 參數預覽
find /var/www/ -type f -mtime +30 -print -exec rm -f '{} \;

保留近期文件的目錄結構

# 僅刪除文件,保留空目錄
find /data/cache/ -type f -mtime +1 -delete

最佳實踐建議

  • ✅ 測試命令用 -print 代替 -exec rm 預覽結果
  • ✅ 重要目錄設置較長保留期(如 90 天)
  • ✅ 記錄清理日誌:> /var/log/cleanup.log 2>&1
  • ✅ 避免清理系統關鍵目錄(/etc、/lib、/boot 等)
  • ✅ 考慮使用 tmpwatch 或 logrotate 替代方案

常見陷阱

  • ❌ -mtime 基於 修改時間,非創建時間
  • ❌ -exec 末尾分號需轉義 \; 或用 + 批量執行
  • ❌ 權限不足導致刪除失敗,需 root 執行

建立自動化清理機制,讓服務器磁盤空間始終保持健康狀態。

Copyright © Windows教程網 All Rights Reserved