Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux 檔案查找神器:which、whereis、locate 深度解析與實戰對比

編輯:Linux 系統常見問題解答

為什麼不直接用 find?

find 遍歷磁盤即時查找,功能最強但速度最慢。which、whereis、locate 利用預建索引/資料庫查詢,速度快數量級,是日常運維首選。本文深度解析三者差異、適用場景與進階技巧。

核心差異總覽表

指令查找範圍資料來源速度適用場景
which僅 $PATH 目錄下的可執行檔即時掃描 $PATH極快確認命令完整路徑、別名展開
whereis二進制、源碼、手冊頁預建資料庫極快查找命令全套檔案位置
locate全系統任意檔案名mlocate.db 索引庫最快模糊查找任意檔案、配置檔、日誌
find指定目錄遞歸所有檔案即時遍歷磁盤最慢複雜條件查找(時間、大小、權限、內容)

1. which - 命令路徑定位器

基本語法

which [-a] command_name
  • -a:列出所有匹配項(預設只顯示第一個)

實戰範例

$ which grep
/bin/grep

$ which -a python
/usr/bin/python
/usr/local/bin/python

$ which ll
alias ll='ls -l --color=auto'
/bin/ls

亮點:自動展開 shell 別名,顯示別名定義與最終執行檔路徑。

進階技巧

# 獲取命令所在目錄(用於腳本動態引用)
CMD_DIR=$(dirname $(which docker))
echo "Docker 安裝目錄: $CMD_DIR"

# 判斷命令是否存在
if which docker &>/dev/null; then
    echo "Docker 已安裝"
else
    echo "請先安裝 Docker"
fi

2. whereis - 命令全景檔案查找器

基本語法

whereis [-bmsu] [-BMS 目錄...] -f 檔案名...
選項功能
-b只查二進制執行檔
-m只查手冊頁
-s只查源碼檔
-u查找異常檔案(無手冊、無源碼、無二進制)
-B 目錄限定二進制搜尋目錄
-M 目錄限定手冊搜尋目錄
-S 目錄限定源碼搜尋目錄

實戰範例

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

$ whereis -b grep
grep: /bin/grep

$ whereis -m grep
grep: /usr/share/man/man1/grep.1.gz /usr/share/man/man1p/grep.1p.gz

# 自定義搜尋路徑
$ whereis -B /opt/local/bin -f nginx
nginx: /opt/local/bin/nginx

3. locate - 全系統檔案名秒級查找

工作原理

系統定時任務(通常每天一次 /etc/cron.daily/mlocate)執行 updatedb 掃描全盤建立 /var/lib/mlocate/mlocate.db 索引庫。locate 直接查詢此資料庫,故極快但可能不含最新檔案。

基本語法

locate [-i] [-r] [-c] [-n 數量] 關鍵字
選項功能
-i忽略大小寫
-r使用正則表達式
-c只顯示匹配計數
-n N限制輸出前 N 條
-e只顯示當前存在的檔案(即時檢查)
-S顯示資料庫統計資訊

實戰範例

$ locate passwd
/etc/passwd
/etc/passwd-
/usr/bin/passwd
/usr/share/man/man1/passwd.1.gz
...

$ locate -i nginx.conf
/etc/nginx/nginx.conf
/opt/nginx/conf/nginx.conf

$ locate -r '\.log$' | head -20
/var/log/syslog
/var/log/nginx/access.log
...

$ locate -c bashrc
3

$ locate -S
Database /var/lib/mlocate/mlocate.db:
    2,345,678 directories
    18,945,321 files
    1.2 GB bytes in file names
    Last updated: Mon Jan 20 06:25:00 2025

手動更新資料庫

sudo updatedb
# 或指定配置
sudo updatedb --localpaths='/home /opt' --prunepaths='/tmp /var/tmp /proc /sys'

配置檔:/etc/updatedb.conf 控制掃描路徑、排除路徑、檔案系統類型等。

實戰場景選型指南

🎯 場景決策樹

  • 「這個命令裝在哪?用哪個版本?」→ which
  • 「這命令的 man page 在哪?源碼在哪?」→ whereis
  • 「系統裡哪裡有包含 nginx 的檔案?」→ locate nginx
  • 「找 7 天前修改、大於 100M、屬於 root 的 .log 檔」→ find
  • 「確認某檔案當前是否真實存在」→ locate -e 或 test -f

常見坑點與避坑指南

坑點原因解決
locate 找不到剛建立的檔案資料庫未更新執行 sudo updatedb 或等待定時任務
locate 顯示已刪除的檔案資料庫過期加 -e 參數即時驗證存在性
which 找不到明明存在的命令命令不在 $PATH 中用 find / -name cmd 2>/dev/null 或 locate cmd
whereis 找不到手冊頁未安裝 man-pages 或路徑不在資料庫安裝 man-db man-pages,執行 mandb

總結

掌握 which、whereis、locate 三劍客,能將日常檔案查找效率提升 90% 以上。記住核心心法:which 找命令路徑,whereis 找命令全家桶,locate 找全盤檔案名。複雜條件查找才請出 find 重型武器。配合 updatedb 定時維護索引,讓查找永遠快人一步。

Copyright © Windows教程網 All Rights Reserved