服務器運行久了,日誌、臨時文件堆積佔用磁盤空間。本文教你用 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 預覽結果> /var/log/cleanup.log 2>&1/etc、/lib、/boot 等)tmpwatch 或 logrotate 替代方案-mtime 基於 修改時間,非創建時間-exec 末尾分號需轉義 \; 或用 + 批量執行建立自動化清理機制,讓服務器磁盤空間始終保持健康狀態。