Linux 提供多種尋找檔案/指令的工具,各有適用場景與優缺點。本文詳細比較 find、locate、whereis、which、type 五大指令,助你根據需求選擇最適合的工具。

| 指令 | 搜尋範圍 | 速度 | 資料來源 | 適用場景 |
|---|---|---|---|---|
find | 即時掃描檔案系統 | 較慢 | 實際磁碟 | 精確條件搜尋、批次處理、即時結果 |
locate | 預建資料庫 | 極快 | /var/lib/mlocate.db | 快速依名稱定位、不需即時結果 |
whereis | 特定目錄(二進位、man、源碼) | 快 | 預定路徑 | 定位指令的執行檔、文件、源碼 |
which | PATH 環境變數目錄 | 快 | PATH 變數 | 確認指令實際執行位置、別名檢查 |
type | Shell 內建/別名/外部指令 | 極快 | Shell 內部 | 判斷指令類型、顯示內建/別名定義 |
find —— 最強大、最即時# 基本語法
find [路徑] [條件] [動作]
# 常用範例
find . -name "my*" # 當前目錄遞迴找 my 開頭檔案
find . -name "my*" -ls # 顯示詳細資訊
find . -type f -mmin -10 # 10 分鐘內修改過的一般檔案
find /var/log -name "*.log" -size +10M -exec gzip {} \;
特點:支援極豐富條件(名稱、類型、時間、權限、大小、擁有者等),可配合 -exec/xargs 執行後續動作,但大範圍搜尋較慢。
locate —— 秒級定位# 基本用法
locate /etc/sh # 找 /etc 下 sh 開頭檔案
locate ~/m # 家目錄下 m 開頭
locate -i ~/m # 忽略大小寫
# 更新資料庫(需 root)
updatedb
原理:每日定時任務更新 /var/lib/mlocate.db,故無法找到最新建立的檔案。使用前先執行 updatedb 可緩解。
whereis —— 定位指令相關檔案whereis grep
# 輸出:grep: /usr/bin/grep /usr/share/man/man1/grep.1.gz
# 限定類型
whereis -b grep # 只找二進位
whereis -m grep # 只找 man page
whereis -s grep # 只找源碼
適用於快速確認指令安裝位置與文件位置。
which —— 確認實際執行路徑which grep
# 輸出:/usr/bin/grep
# 檢查別名
alias ll='ls -l'
which ll # 無輸出(因為是別名)
type ll # 顯示別名定義
只搜尋 PATH 中的目錄,回傳第一個找到的執行檔,適合驗證「輸入指令到底執行哪個版本」。
type —— 判斷指令本質type cd
# cd is a shell builtin
type grep
# grep is /usr/bin/grep
type -p grep
# 相當於 which grep
type 能區分 Shell 內建指令、別名、函數、外部執行檔,加 -p 時僅顯示外部指令路徑。
find /etc -name "*.conf" 或 locate *.confpython 指向哪個版本」→ which python 或 type -p pythonls 的 man page 位置」→ whereis -m lscd 是內建還是外部」→ type cdfind / -type f -size +100M -exec ls -lh {} \; | sort -k5 -hr | head五大指令各司其職:find 最全能但較慢,locate 極快但非即時,whereis/which 專注指令定位,type 剖析指令本質。實務上常搭配使用,例如先 locate 粗略定位,再 find 精確過濾並處理。