Linux 哲學「一切皆檔案」,高效定位檔案是系統管理與開發的基本功。本文系統整理五大尋找工具的適用場景、核心參數與實戰範例,助您精準、高速鎖定目標。
直接掃描磁碟目錄樹,支援豐富條件(名稱、類型、權限、時間、大小、擁有者等)與後續動作(刪除、執行命令等)。
find [搜尋路徑] [條件表達式] [動作]
| 參數 | 說明 | 範例 |
|---|---|---|
-name pattern | 檔名匹配(支援 * ?),建議加引號 | -name '*.log' |
-iname pattern | 忽略大小寫的檔名匹配 | -iname 'readme*' |
-type f/d/l | 檔案類型:一般檔/目錄/符號連結 | -type f |
-size n[c/k/M/G] | 檔案大小(+大於 -小於),預設 512-byte 區塊 | -size +100M |
-mtime n | 修改時間:n 天前(+n 超過,-n 內) | -mtime -7 (7天內) |
-atime n | 存取時間 | -atime +30 |
-user name | 擁有者用戶名 | -user www |
-perm mode | 權限匹配 | -perm 644 |
-exec cmd {} \; | 對結果執行命令({} 佔位,以 \; 結尾) | -exec rm {} \; |
# 1. 全系統找 httpd.conf
find / -name httpd.conf -print
# 2. 部分檔名模糊搜尋
find / -name '*http*' -print
# 3. /etc 下找小於 2500 bytes 的檔案
find /etc -size -2500c -print
# 4. 當前目錄 10 分鐘內修改過的一般檔案
find . -type f -mmin -10
# 5. 找出屬於 user1 且權限 755 的執行檔
find /home -user user1 -perm 755 -type f
不掃描磁碟,而是查詢預建索引資料庫(/var/lib/mlocate/mlocate.db),速度極快,但無法找到最新建立/變動的檔案。
# 手動更新資料庫(需 root)
updatedb
# 使用範例
locate /etc/sh # /etc 目錄下以 sh 開頭
locate ~/m # 家目錄下以 m 開頭
locate -i ~/m # 忽略大小寫
僅搜尋標準系統目錄,適合確認指令安裝位置與文件。
whereis grep
# 輸出:grep: /usr/bin/grep /usr/share/man/man1/grep.1.gz
# 限定類型
whereis -b grep # 僅二進制
whereis -m grep # 僅 man page
whereis -s grep # 僅原始碼
回傳 $PATH 中第一個匹配的可執行檔路徑,驗證「執行的是哪個版本」。
which grep
# /usr/bin/grep
區分 Shell 內建 vs 外部可執行檔,搭配 -p 等同 which。
type cd # cd is a shell builtin
type grep # grep is /usr/bin/grep
type -p grep # /usr/bin/grep
updatedb)# 安全處理含空白/特殊字元的檔名
find . -name '*.tmp' -print0 | xargs -0 rm -f
# 並行加速刪除
find /var/log -name '*.log' -mtime +30 -print0 | parallel -0 rm -f
掌握五大工具的分工與組合,能讓您在茫茫檔案系統中如魚得水。日常運維建議:locate 找大方向,find 精準定位並處理,which/type 驗證執行環境。