find 是 Linux 最強大的檔案搜尋工具,支援依名稱、類型、時間、大小、權限、擁有者等多維度條件組合,並可配合 -exec 執行批次操作。本文精選 10 大核心技巧,附實戰範例與最佳實踐。
# 精確副檔名
find . -name "*.txt" -print
# 多條件 OR (需逃脫括號)
find . \( -name "*.txt" -o -name "*.log" \) -print
# 忽略大小寫
find . -iname "readme*" -print
# 路徑匹配 (含目錄名)
find . -path "*/test/*.txt" -print
# 排除 .txt 檔案
find . ! -name "*.txt" -print
# 或
find . -not -name "*.txt" -print
# 僅當前目錄 (深度 1)
find . -maxdepth 1 -type f -print
# 排除前 2 層,從第 3 層開始
find . -mindepth 3 -type f -print
# 組合:僅搜尋第 2~3 層
find . -mindepth 2 -maxdepth 3 -type f -print
關鍵:-maxdepth/-mindepth 必須緊跟在起始路徑後。
find . -type f -print # 普通檔案
find . -type d -print # 目錄
find . -type l -print # 符號連結
find . -type c -print # 字元裝置
find . -type b -print # 區塊裝置
find . -type s -print # Socket
find . -type p -print # FIFO/管道
三種時間:atime (存取)、mtime (內容修改)、ctime (元資料變更)。單位:天。+n 大於 n 天,-n 小於 n 天,n 等於 n 天。分鐘版對應 -amin/-mmin/-cmin。
# 正好 7 天前存取
find . -type f -atime 7
# 超過 7 天未修改
find . -type f -mtime +7
# 7 天內內容有變動
find . -type f -mtime -7
# 分鐘級:30 分鐘內修改
find . -type f -mmin -30
# 比參考檔案更新 (mtime)
find . -type f -newer reference.txt -print
單位:b (512B 區塊)、c (Byte)、w (2B 字)、k (KB)、M (MB)、G (GB)。
# 等於 2MB
find . -type f -size 2M
# 大於 2MB
find . -type f -size +2M
# 小於 2MB
find . -type f -size -2M
# 範圍:1MB ~ 10MB
find . -type f -size +1M -size -10M
# 刪除當前目錄下所有 .swp 暫存檔
find . -type f -name ".*.swp" -delete
# 安全模式:先列印確認再刪除
find . -type f -name ".*.swp" -print -delete
警告:-delete 立即生效且無法復原,生產環境必先 -print 確認。
# 權限精確匹配 644
find . -type f -perm 644 -print
# 權限包含 (至少包含該權限)
find . -type f -perm -644 -print
# 擁有者為 reed
find . -type f -user reed -print
# 群組為 developers
find . -type f -group developers -print
# 將 reed 擁有的檔案改屬 cathy
find . -type f -user reed -exec chown cathy {} \;
# 備份 10 天前的 .log 檔至 /data/bk_log
find . -type f -mtime +10 -name "*.log" -exec cp {} /data/bk_log \;
# 列出所有 .txt 檔案完整路徑 (格式化輸出)
find /tmp/test -type f -name "*.txt" -exec printf "Text file: %s\n" {} \;
{} 會被替換為當前匹配檔案路徑。\; 結束 -exec,需跳脫分號。+ 替代 \; 批次傳遞多檔案 (如 cp {} +),減少進程啟動開銷。
-prune:命中時不再遞入該目錄。-o (OR) 結合其餘條件,結構為 (排除條件 -prune) -o (正常處理條件)。
尋找 /var/log 下超過 30 天、大於 10MB、屬於 root 的 .log 檔案並壓縮歸檔:
find /var/log -type f -name "*.log" -mtime +30 -size +10M -user root \
-exec gzip {} \; -exec mv {}.gz /archive/logs/ \;
總結:掌握 find 的條件組合、深度控制、時間/大小/權限匹配、-exec 批次處理與 -prune 剪枝,即可應對 99% 檔案搜尋與批次操作需求。