萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 尋找檔案的 5 大指令比較:find、locate、whereis、which、type

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

快速比較表

指令搜尋範圍速度資料來源適用場景
find即時掃描檔案系統較慢實際磁碟精確條件搜尋、批次處理、即時結果
locate預建資料庫極快/var/lib/mlocate.db快速依名稱定位、不需即時結果
whereis特定目錄(二進位、man、源碼)快預定路徑定位指令的執行檔、文件、源碼
whichPATH 環境變數目錄快PATH 變數確認指令實際執行位置、別名檢查
typeShell 內建/別名/外部指令極快Shell 內部判斷指令類型、顯示內建/別名定義

詳細用法與範例

1. 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 執行後續動作,但大範圍搜尋較慢。

2. locate —— 秒級定位

# 基本用法
locate /etc/sh               # 找 /etc 下 sh 開頭檔案
locate ~/m                   # 家目錄下 m 開頭
locate -i ~/m                # 忽略大小寫

# 更新資料庫(需 root)
updatedb

原理:每日定時任務更新 /var/lib/mlocate.db,故無法找到最新建立的檔案。使用前先執行 updatedb 可緩解。

3. 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   # 只找源碼

適用於快速確認指令安裝位置與文件位置。

4. which —— 確認實際執行路徑

which grep
# 輸出:/usr/bin/grep

# 檢查別名
alias ll='ls -l'
which ll   # 無輸出(因為是別名)
type ll    # 顯示別名定義

只搜尋 PATH 中的目錄,回傳第一個找到的執行檔,適合驗證「輸入指令到底執行哪個版本」。

5. 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 *.conf
  • 「確認 python 指向哪個版本」→ which python 或 type -p python
  • 「查看 ls 的 man page 位置」→ whereis -m ls
  • 「判斷 cd 是內建還是外部」→ type cd
  • 「找出佔用空間最大的 10 個檔案」→ find / -type f -size +100M -exec ls -lh {} \; | sort -k5 -hr | head

小結

五大指令各司其職:find 最全能但較慢,locate 極快但非即時,whereis/which 專注指令定位,type 剖析指令本質。實務上常搭配使用,例如先 locate 粗略定位,再 find 精確過濾並處理。

copyright © 萬盛學電腦網 all rights reserved