尋找指令、二進位檔、原始碼、手冊頁路徑時,which、whereis、locate 各有專長,本文詳細對比三者機制與適用場景。
| 工具 | 搜尋來源 | 速度 | 搜尋範圍 | 典型用途 |
|---|---|---|---|---|
| which | 環境變數 $PATH | 極快 | 僅 $PATH 目錄下的執行檔 | 確認命令實際執行路徑、別名檢查 |
| whereis | 預建資料庫 (二進位/原始碼/手冊頁固定目錄) | 極快 | 標準系統目錄 (/bin, /usr/bin, /usr/share/man 等) | 尋找二進位、原始碼、man page 完整路徑 |
| locate | 全檔案系統資料庫 (/var/lib/mlocate/mlocate.db) | 極快 | 全系統 (含家目錄、掛載點) | 模糊搜尋檔名、尋找非標準路徑檔案 |
| find | 即時掃描磁碟 | 較慢 | 指定路徑遞迴 | 精確條件搜尋 (大小、時間、權限、類型) |
which ls
# /bin/ls
which -a ls
# /bin/ls
# /usr/bin/ls (列出所有 PATH 中同名命令)
which ll
# alias ll='ls -l --color=auto'
# /bin/ls (同時顯示別名定義與實際路徑)
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
whereis -s grep # 僅原始碼 (通常無)
# grep:
# 手動更新資料庫 (需 root)
updatedb
# 模糊搜尋
locate passwd
# /etc/passwd
# /usr/bin/passwd
# /usr/share/man/man1/passwd.1.gz
# /home/user/.ssh/known_hosts (含 passwd 字串)
# 精確匹配檔名 (搭配 basename)
locate -b '\passwd'
# 僅輸出檔名為 passwd 的路徑
# 統計數量
locate -c nginx.conf
資料庫更新排程:/etc/cron.daily/mlocate 每日自動執行 updatedb。配置檔 /etc/updatedb.conf 可設定排除路徑 (PRUNEPATHS)。
# 結合使用:找到命令後查看手冊
man $(whereis -m ls | awk '{print $2}')
# locate 排除掛載點
locate -e pattern # 僅輸出當前存在的路徑 (忽略已刪除)