find 是 Linux 下最強大的檔案搜尋工具之一,掌握它的常用參數,幾乎能應付所有找檔案的場景。以下整理 12 個最實用的參數,並附上具體用法。
name 是最常用的選項,可單獨使用或搭配其他選項。使用檔名比對時記得用引號包住。不論目前路徑為何,若想在自己的家目錄找 *.log,可用 ~ 代表 $HOME:
find ~ -name "*.log" -print
在目前及子目錄找所有 *.log:
find . -name "*.log" -print
找檔名以大寫字母開頭的檔案:
find . -name "[A-Z]*" -print
在 /etc 找檔名以 host 開頭的檔案:
find /etc -name "host*" -print
列出家目錄所有檔案:
find ~ -name "*" -print 或 find . -print
從根目錄找全部檔案(會讓系統高負載):
find / -name "*" -print
在目前目錄找檔名以小寫字母開頭、以 4–9 加 .log 結尾的檔案:
find . -name "[a-z]*[4-9].log" -print
輸出範例:
[root@localhost test]# find . -name "[a-z]*[4-9].log" -print
./log2014.log
./log2015.log
./test4/log2014.log
用 -perm 依權限模式找檔,建議採用八進位表示法。例如找權限為 755 的檔案:
[root@localhost test]# find . -perm 755 -print
另一種寫法是在八進位數字前加一橫槓,代表「全部符合」,如 -005 相當於 555:
[root@localhost test]# find . -perm -005
若確定某目錄沒有要找的檔案,可用 -prune 排除。注意:若同時使用 -depth,-prune 會被忽略。例如要在 test 下搜尋但跳過 test/test3:
find test -path "test/test3" -prune -o -print
在 test 下找不在 test4 內的所有檔案:
find test -path "test/test4" -prune -o -print
其原理是 find [-path ..] [expression],-a 與 -o 皆為短路求值,類似 shell 的 && 與 ||。當 -path "test" 為真便求值 -prune 並回傳真;否則改求值 -print。可用偽碼理解:
if -path "test" then
-prune
else
-print
避開多個資料夾:
find test \( -path test/test4 -o -path test/test3 \) -prune -o -print
括號代表運算式分組,\ 則是轉義,指示 shell 別對後面字元做特殊解讀,留給 find 處理。若只想找特定檔,把 -name 加在 -o 之後:
find test \( -path test/test4 -o -path test/test3 \) -prune -o -name "*.log" -print
在家目錄找屬主為 peida 的檔案:
find ~ -user peida -print
在 /etc 找屬主為 peida 的檔案:
find /etc -user peida -print
找出屬主帳號已被刪除的檔案,可用 -nouser(不必給使用者名稱):
find /home -nouser -print
在 /apps 找屬於 gem 群組的檔案:
find /apps -group gem -print
找出沒有有效所屬群組的檔案:
find / -nogroup -print
可用 mtime、atime 或 ctime。若系統突然沒空間,可能是某檔急速膨脹,可用 mtime 排查。減號 - 限定 n 天內,加號 + 限定 n 天以前。找根目錄下 5 天內修改的檔案:
find / -mtime -5 -print
在 /var/adm 找 3 天前修改的檔案:
find /var/adm -mtime +3 -print
用 -newer,一般形式為:
newest_file_name ! oldest_file_name
其中 ! 為邏輯非。找比 log2012.log 新、比 log2017.log 舊的檔案:
find -newer log2012.log ! -newer log2017.log
找比 log2012.log 新的檔案:
find . -newer log2012.log -print
在 /etc 找所有目錄:
find /etc -type d -print
在目前目錄找非目錄的檔案:
find . ! -type d -print
在 /etc 找所有符號連結:
find /etc -type l -print
檔案長度可用位元組(N c)或區塊(純數字)表示。找大於 1M 位元組的檔案:
find . -size +1000000c -print
找恰好 100 位元組的檔案:
find /home/apache -size 100c -print
找超過 10 個區塊(每塊 512 位元組)的檔案:
find . -size +10 -print
使用 depth 可讓 find 先比對所有檔案再進入子目錄,這在備份到磁帶時特別有用(先備份檔案、再備份目錄)。從根目錄找名為 CON.FILE 的檔案:
find / -name "CON.FILE" -depth -print
只在目前檔案系統搜尋、不進入其他檔案系統,可用 mount。從目前目錄找檔名以 XC 結尾的檔案:
find . -name "*.XC" -mount -print