萬盛學電腦網

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

Linux whereis 指令快速定位二進制/原始碼/手冊頁:比 find 快 100 倍的秘密

whereis 專門定位「程式相關檔案」:二進制執行檔、原始碼、man 手冊頁。它不掃描磁碟,而是查詢預建資料庫,速度極快,是管理員尋找指令位置的首選工具。

語法與參數

whereis [-bmsu] [-BMS 目錄] -f 檔案名
  -b   只找二進制檔
  -m   只找手冊頁
  -s   只找原始碼
  -u   找不尋常檔案 (無上述三類)
  -B   指定二進制搜尋路徑
  -M   指定手冊頁搜尋路徑
  -S   指定原始碼搜尋路徑
  -f   結束目錄參數,開始檔案名 (配合 -B/-M/-S)

核心原理:預建資料庫

  • 資料庫位置:/var/lib/mlocate/mlocate.db (mlocate) 或 /var/lib/locate/locate.db (舊 locate)
  • 更新機制:/etc/cron.daily/mlocate 每日執行 updatedb
  • 優點:毫秒級查詢、不讀取磁碟
  • 缺點:非即時 (新檔案需待 updatedb)、不支援複雜條件 (大小、時間、權限)

實戰範例

# 1. 完整查詢 (三類皆找)
whereis nginx
# nginx: /usr/sbin/nginx /usr/lib/nginx/modules /etc/nginx /usr/share/man/man8/nginx.8.gz

# 2. 只找二進制
whereis -b nginx
# nginx: /usr/sbin/nginx /usr/lib/nginx/modules

# 3. 只找手冊頁
whereis -m nginx
# nginx: /usr/share/man/man8/nginx.8.gz

# 4. 只找原始碼 (通常套件不含原始碼,除非安裝 src.rpm/deb-src)
whereis -s nginx
# nginx:

# 5. 指定搜尋路徑
whereis -B /opt/nginx/sbin -f nginx

whereis 輸出範例

whereis vs find vs locate 三大查找工具對比

特性whereislocatefind
搜尋對象程式三件套 (bin/man/src)所有檔案 (檔名)所有檔案 (屬性/內容/類型)
速度極快 (資料庫)極快 (資料庫)慢 (掃描磁碟)
即時性非即時非即時即時
條件豐富度低低 (支援正則)極高 (型別/大小/時間/權限/深度/執行動作)
典型用途確認指令安裝位置、man 頁位置模糊記得檔名找路徑精確條件搜尋、批次處理

進階技巧

  • 手動更新資料庫:updatedb (需 root)
  • 排除路徑:/etc/updatedb.conf 設定 PRUNEPATHS
  • 搭配 xargs 批次操作:whereis -b nginx | cut -d: -f2 | xargs ls -l
  • 驗證指令來源:whereis -b ls → /usr/bin/ls → rpm -qf /usr/bin/ls (核對套件)

適用場景決策樹

知道程式名,要找執行檔/man page 位置 → whereis
模糊記得檔名關鍵字,要找路徑 → locate
需按大小/時間/型別/權限/內容搜尋 → find
需即時結果 → find (或 fd/ripgrep)

whereis 專注、極速、零負擔,是「確認指令安裝狀態」的黃金工具。善用 -b/-m/-s 精準鎖定所需檔案類別。

copyright © 萬盛學電腦網 all rights reserved