萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 尋找檔案三大神器:which、whereis、locate 差異與選用指南

尋找指令、二進位檔、原始碼、手冊頁路徑時,which、whereis、locate 各有專長,本文詳細對比三者機制與適用場景。

核心差異總覽

工具搜尋來源速度搜尋範圍典型用途
which環境變數 $PATH極快僅 $PATH 目錄下的執行檔確認命令實際執行路徑、別名檢查
whereis預建資料庫 (二進位/原始碼/手冊頁固定目錄)極快標準系統目錄 (/bin, /usr/bin, /usr/share/man 等)尋找二進位、原始碼、man page 完整路徑
locate全檔案系統資料庫 (/var/lib/mlocate/mlocate.db)極快全系統 (含家目錄、掛載點)模糊搜尋檔名、尋找非標準路徑檔案
find即時掃描磁碟較慢指定路徑遞迴精確條件搜尋 (大小、時間、權限、類型)

which 詳細用法

which ls
# /bin/ls

which -a ls
# /bin/ls
# /usr/bin/ls  (列出所有 PATH 中同名命令)

which ll
# alias ll='ls -l --color=auto'
# /bin/ls    (同時顯示別名定義與實際路徑)

whereis 詳細用法

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:

locate 詳細用法

# 手動更新資料庫 (需 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)。

選用決策樹

  1. 確認命令安裝位置 / 別名 → which
  2. 需同時獲取二進位、原始碼、手冊路徑 → whereis
  3. 模糊記得檔名、跨目錄尋找 → locate
  4. 精確條件 (大小、時間、權限、類型、內容) → find

進階技巧

# 結合使用:找到命令後查看手冊
man $(whereis -m ls | awk '{print $2}')

# locate 排除掛載點
locate -e pattern   # 僅輸出當前存在的路徑 (忽略已刪除)
copyright © 萬盛學電腦網 all rights reserved