whereis 是 Linux/Unix 系統中專門用於快速定位命令相關文件的工具,不同於 find 遍歷磁盤,它查詢預建數據庫,速度極快。本文系統講解參數用法、路徑限制技巧、-u 參數陷阱及源碼級原理分析。
whereis [選項] 命令名
whereis -BMS 目錄 -f 命令名 # 限制搜索路徑
| 參數 | 功能 | 示例 |
|---|---|---|
-b | 僅搜索二進制文件 | whereis -b ls |
-m | 僅搜索手冊頁 | whereis -m ls |
-s | 僅搜索源代碼 | whereis -s ls |
-u | 搜索「異常」文件 (缺少某類文件) | whereis -u -m * |
-B <dir> | 限制二進制搜索路徑 | whereis -B /bin -f ls |
-M <dir> | 限制手冊搜索路徑 | whereis -M /usr/share/man -f ls |
-S <dir> | 限制源碼搜索路徑 | whereis -S /usr/src -f ls |
-f | 終結路徑限制,後接命令名 (配合 -B/-M/-S 必用) | whereis -B /bin -f ls gcc |
| 顯示版本信息 | whereis -V |
$ whereis date
date: /bin/date /usr/share/man/man1/date.1.gz /usr/share/man/man1p/date.1p.gz
$ whereis -b date
date: /bin/date
$ whereis -B /bin -f ls gcc
ls: /bin/ls /usr/share/man/man1/ls.1.gz
gcc:
解讀: gcc 無輸出說明其二進制不在 /bin (實際在 /usr/bin),但手冊頁仍在默認路徑被找到。
man 手冊稱 -u 查找「不包含請求類型文件」的異常項,但實測行為與文檔不符:
$ cd /bin
$ whereis -m -u * # 預期:列出無手冊頁的命令
$ whereis -m * # 實際:結果完全相同
原因分析: 查閱 util-linux 源碼 (whereis.c) 發現,whereis 使用硬編碼搜索路徑,-u 邏輯未正确实現,導致無法正確過濾「缺少手冊」的文件。建議不依賴 -u 參數進行關鍵審計。
/bin, /usr/bin, /sbin, /usr/sbin, /usr/local/bin.../usr/share/man, /usr/local/man, /usr/man.../usr/src, /usr/local/src...$PATH 環境變量,故無法找到自定義路徑命令源碼參考:GitHub whereis.c
| 工具 | 搜索範圍 | 速度 | 用途 |
|---|---|---|---|
whereis | 預定義目錄 (二進制/手冊/源碼) | 極快 (數據庫) | 快速定位系統命令全套文件 |
which | $PATH 環境變量 | 快 | 確認命令實際執行路徑 (含別名) |
find | 指定目錄遞歸遍歷 | 慢 | 精確查找任意文件、支持正則/屬性過濾 |
locate | mlocate 數據庫 | 極快 | 按文件名模糊查找,需 updatedb 更新 |
which cmd 或 type -a cmdwhereis -m cmdwhereis -s cmd 或 rpm -ql pkg | grep \\.c$ (RPM 系統)find /opt -name \"cmd\" -type f -executablecommand -v cmd (POSIX 標準)whereis 是快速定位系統命令「三件套」的利器,但受限於硬編碼路徑與 -u 缺陷,無法替代 find/locate 進行通用文件搜索。掌握 -B/-M/-S -f 路徑限制技巧,能在多版本並存環境中精準鎖定目標文件位置。