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 /path/to/dir -mtime +N -type f -name 'pattern' -exec rm -f {} \;

參數詳細解析

參數含義
/path/to/dir目標目錄(遞迴搜尋)
-mtime +N修改時間超過 N 天(+30 表示 30 天前,不含第 30 天)
-type f僅匹配一般檔案(不含目錄、連結等)
-name 'pattern'檔名模式(支援萬用字元 *、?、[...])
-exec rm -f {} \;對每個結果執行 rm -f;{} 為佔位符,\; 結束

實戰範例

1. 刪除 /tmp 下 30 天前的 .sh/.log 檔

find /tmp -mtime +30 -type f \( -name "*.sh" -o -name "*.log" \) -exec rm -f {} \;

2. 刪除 /var/log 下 7 天前超過 100MB 的 .gz 檔

find /var/log -mtime +7 -type f -name "*.gz" -size +100M -exec rm -f {} \;

3. 使用 xargs 提升大量檔案刪除效能

find /data/backup -mtime +30 -type f -print0 | xargs -0 rm -f

優勢: -print0 + xargs -0 以 null 字元分隔,安全處理含空白/特殊字元的檔名;單次 rm 處理多檔,減少進程啟動開銷。

納入 crontab 定時執行

編輯系統級 crontab

vim /etc/crontab
# 每天凌晨 3:30 清理 /data/logs 30 天前的 .log 檔
30 3 * * * root find /data/logs -mtime +30 -type f -name "*.log" -exec rm -f {} \;

或使用用戶級 crontab

crontab -e
# 每天 02:00 清理
0 2 * * * find /home/user/tmp -mtime +7 -type f -exec rm -f {} \;

進階:刪除前先備份/記錄

#!/bin/bash
# clean_old.sh
TARGET_DIR="/data/logs"
DAYS=30
LOG_FILE="/var/log/clean_old.log"

find "$TARGET_DIR" -mtime +$DAYS -type f -name "*.log" -print0 |
while IFS= read -r -d '' file; do
    echo "$(date '+%F %T') 刪除: $file" >> "$LOG_FILE"
    rm -f "$file"
done

給予執行權限 chmod +x clean_old.sh,crontab 呼叫腳本即可。

常見陷阱提醒

  • -mtime +0 表示「超過 0 天」即 24 小時前,而非「今天」。
  • -ctime(inode 變更時間)≠ -mtime(內容修改時間)≠ -atime(存取時間),請根據業務選擇。
  • 目錄本身不會被 -type f 刪除,但空目錄會殘留,需定期 find -type d -empty -delete 清理。
  • 權限不足:crontab 執行身份需具備目標目錄的 x(進入)與 w(刪除檔案)權限。

總結

find -mtime +N -type f -exec rm -f {} \; 是 Linux 定時清理舊檔的標準組合。搭配 xargs 提升效能、-print0 處理特殊檔名、crontab 定時自動化、腳本記錄審計,即可構建安全、高效、可追蹤的檔案生命週期管理機制。

Copyright © Windows教程網 All Rights Reserved