Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 查找檔案五大指令詳解:find、locate、whereis、which、type

編輯:關於 Linux

在 Linux 系統中尋找檔案是基本功,但不同工具適用場景差異極大。本文深度解析 find、locate、whereis、which、type 五大查找指令的語法、參數與實戰範例,助你精準選擇最高效的工具。

Linux 查找指令對比

1. find — 最強大、最靈活的即時搜尋

find 直接掃描磁碟目錄樹,支援極豐富的條件判斷與後續動作,適合精確、複雜的搜尋需求。

基本語法

find [指定目錄] [指定條件] [指定動作]
  • 指定目錄:預設為當前目錄,遞歸包含所有子目錄。
  • 指定條件:檔名、類型、大小、時間、權限、擁有者等。
  • 指定動作:-print (預設)、-ls、-exec command {} \;、-delete 等。

經典範例

  • find . -name 'my*':當前目錄下找檔名以 my 開頭的檔案
  • find . -name 'my*' -ls:並顯示詳細屬性
  • find . -type f -mmin -10:找 10 分鐘內修改過的一般檔案 (-type f 排除目錄)
  • find / -name "*.rpm" -exec chmod 755 {} \;:找到所有 .rpm 檔並修改權限
  • find / -xdev -name "*.rpm":搜尋時忽略跨檔案系統 (如光碟、USB)

2. locate — 秒級回應的資料庫搜尋

locate 不掃描磁碟,而是查詢預建索引資料庫 (/var/lib/locatedb),速度極快,但無法找到最新建立/變動的檔案。

使用技巧

  • 搜尋前執行 updatedb 手動更新資料庫
  • locate /etc/sh:找 /etc 下以 sh 開頭的檔案
  • locate ~/m:找家目錄下以 m 開頭的檔案
  • locate -i ~/m:忽略大小寫

3. whereis — 專門定位程式二進制、原始碼、手冊頁

僅搜尋預設系統目錄,適合確認指令安裝位置與文件。

  • whereis -b:只找二進制檔
  • whereis -m:只找手冊頁
  • whereis -s:只找原始碼
  • 無參數則顯示全部

範例

$ whereis grep
grep: /usr/bin/grep /usr/share/man/man1/grep.1.gz

4. which — 在 PATH 中尋找可執行檔完整路徑

只回傳第一個符合的路徑,常用於確認「到底執行的是哪個版本」或「指令是否存在」。

範例

$ which grep
/usr/bin/grep

5. type — 判斷指令來源:內建 vs 外部

type 不是搜尋工具,而是識別指令屬於 Shell 內建 (build-in) 還是外部二進制檔。

  • type cd → cd is a shell builtin
  • type grep → grep is /usr/bin/grep
  • type -p grep:等同 which grep,只顯示外部指令路徑

總結:如何選擇?

指令速度資料即時性適用場景
find慢即時複雜條件、需對結果執行動作、尋找最新檔案
locate極快延遲 (每日更新)快速模糊搜尋檔名、不需即時結果
whereis快即時定位指令的二進制、man page、source code
which快即時確認 PATH 中指令的實際執行路徑
type極快即時區分內建/外部指令、獲取外部指令路徑

掌握這五把「尋檔利器」,無論是排查系統問題、開發除錯還是日常運維,都能事半功倍。

Copyright © Windows教程網 All Rights Reserved