Linux 下的 find 指令在目錄結構中搜尋檔案並執行指定操作,提供了很多查找條件,功能非常強大。
1. 命令格式:
find pathname -options [-print -exec -ok ...]
2. 命令功能:在檔案樹中查找檔案並做出相應處理(可能存取磁碟)。
3. 命令參數:
pathname:所查找的目錄路徑,用 . 表示當前目錄,用 / 表示系統目錄。
-print:將匹配的檔案輸出到標準輸出。
-exec:對匹配檔案執行所給出的 shell 命令,形式為 'command' { } \;,注意 { } 與 \; 之間的空格。
-ok:與 -exec 相同,但以更安全模式執行,每個命令執行前都會提示確認。
常用選項:-name 按名字查找;-perm 按權限查找;-prune 不在當前指定目錄下查找;-user 按屬主查找;-group 按所屬組查找;-mtime -n +n 按更改時間查找;-nogroup 查找無有效所屬組的檔案;-nouser 查找無有效屬主的檔案;-type 查找特定類型的檔案。

以下用簡單例子介紹 find 的常規用法。
1. 按名字查找
1)查找檔名為 test.c 的檔案:
[admin@bogon ~]$ find -name test.c ./test.c

2)查找檔名包含 test 的檔案:
[admin@bogon ~]$ find -name 'test' ./test ./BIT/test

3)在 $HOME 及其子目錄中查找所有檔案:
[admin@bogon ~]$ find ~ -name '*' -print

4)條件式查找:-a 與、-o 或、-not 非(等同否定參數 '!')。
find -name "t*" -a -name "*.c" # 以 t 開頭且以 .c 結尾 find -name "t*" -o -name "*.c" # 以 t 開頭或以 .c 結尾 find ./ ! -name '*.c' -print # 不以 .c 結尾 find -name "t*" -not -name "*.c" # 以 t 開頭但不以 .c 結尾



2. 依檔案類型搜索:普通檔案 f、符號檔案 l、目錄 d、字符設備 c、塊設備 b、套接字 s、管道 p。

3. 依檔案大小:-size 可透過大小查找,-size n[c] 中帶 c 時以位元組計,單位有 b(512 位元組)、c(位元組)、w(字)、k、M、G。
[admin@bogon ~]$ find -size +18k # 比 18k 大 [admin@bogon ~]$ find -size -18k # 比 18k 小


4. 依檔案深度查找:-maxdepth 與 -mindepth 用來限定搜尋深度。
find -maxdepth 2 -name test # 在深度 1 的子目錄中查找

5. 依檔案權限查找:-perm。
find -perm 664

6. 依檔案時間查找:Linux 檔案系統中每個檔案都有三種時間戳:
1. 訪問時間(atime):上次訪問該檔案的時間。
2. 改變時間(ctime):檔案 inode 改變的時間,新增/刪除數據、變更所有者、鏈接改變時都會改變。
3. 修改時間(mtime):檔案內容上次發生改變的時間。
[admin@bogon ~]$ find -type f -atime -2 # 兩天內訪問 [admin@bogon ~]$ find -atime +10 # 十天前訪問 find ./ -newer test.c # 比 test.c 還新的檔案


