find?find 遍歷磁盤即時查找,功能最強但速度最慢。which、whereis、locate 利用預建索引/資料庫查詢,速度快數量級,是日常運維首選。本文深度解析三者差異、適用場景與進階技巧。
| 指令 | 查找範圍 | 資料來源 | 速度 | 適用場景 |
|---|---|---|---|---|
| which | 僅 $PATH 目錄下的可執行檔 | 即時掃描 $PATH | 極快 | 確認命令完整路徑、別名展開 |
| whereis | 二進制、源碼、手冊頁 | 預建資料庫 | 極快 | 查找命令全套檔案位置 |
| locate | 全系統任意檔案名 | mlocate.db 索引庫 | 最快 | 模糊查找任意檔案、配置檔、日誌 |
| find | 指定目錄遞歸所有檔案 | 即時遍歷磁盤 | 最慢 | 複雜條件查找(時間、大小、權限、內容) |
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
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
系統定時任務(通常每天一次 /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 控制掃描路徑、排除路徑、檔案系統類型等。
| 坑點 | 原因 | 解決 |
|---|---|---|
| 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 定時維護索引,讓查找永遠快人一步。