萬盛學電腦網

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

Linux 尋找檔案五大神器:find、locate、whereis、which、type 完全指南

前言

Linux 哲學「一切皆檔案」,高效定位檔案是系統管理與開發的基本功。本文系統整理五大尋找工具的適用場景、核心參數與實戰範例,助您精準、高速鎖定目標。

1. find — 最強大、最靈活的即時搜尋

直接掃描磁碟目錄樹,支援豐富條件(名稱、類型、權限、時間、大小、擁有者等)與後續動作(刪除、執行命令等)。

基本語法

find [搜尋路徑] [條件表達式] [動作]

常用條件表達式速查

參數說明範例
-name pattern檔名匹配(支援 * ?),建議加引號-name '*.log'
-iname pattern忽略大小寫的檔名匹配-iname 'readme*'
-type f/d/l檔案類型:一般檔/目錄/符號連結-type f
-size n[c/k/M/G]檔案大小(+大於 -小於),預設 512-byte 區塊-size +100M
-mtime n修改時間:n 天前(+n 超過,-n 內)-mtime -7 (7天內)
-atime n存取時間-atime +30
-user name擁有者用戶名-user www
-perm mode權限匹配-perm 644
-exec cmd {} \;對結果執行命令({} 佔位,以 \; 結尾)-exec rm {} \;

實戰範例

# 1. 全系統找 httpd.conf
find / -name httpd.conf -print

# 2. 部分檔名模糊搜尋
find / -name '*http*' -print

# 3. /etc 下找小於 2500 bytes 的檔案
find /etc -size -2500c -print

# 4. 當前目錄 10 分鐘內修改過的一般檔案
find . -type f -mmin -10

# 5. 找出屬於 user1 且權限 755 的執行檔
find /home -user user1 -perm 755 -type f

2. locate — 秒級模糊搜尋(資料庫索引)

不掃描磁碟,而是查詢預建索引資料庫(/var/lib/mlocate/mlocate.db),速度極快,但無法找到最新建立/變動的檔案。

# 手動更新資料庫(需 root)
updatedb

# 使用範例
locate /etc/sh          # /etc 目錄下以 sh 開頭
locate ~/m              # 家目錄下以 m 開頭
locate -i ~/m           # 忽略大小寫

3. whereis — 專門定位二進制、原始碼、man page

僅搜尋標準系統目錄,適合確認指令安裝位置與文件。

whereis grep
# 輸出:grep: /usr/bin/grep /usr/share/man/man1/grep.1.gz

# 限定類型
whereis -b grep  # 僅二進制
whereis -m grep  # 僅 man page
whereis -s grep  # 僅原始碼

4. which — 查詢 PATH 內指令的實際執行路徑

回傳 $PATH 中第一個匹配的可執行檔路徑,驗證「執行的是哪個版本」。

which grep
# /usr/bin/grep

5. type — 判斷指令來源

區分 Shell 內建 vs 外部可執行檔,搭配 -p 等同 which。

type cd      # cd is a shell builtin
type grep    # grep is /usr/bin/grep
type -p grep # /usr/bin/grep

工具選擇決策樹

  1. 找任意檔案、需複雜條件、需即時結果、需後續處理 → find
  2. 找檔名關鍵字、要極快速度、可接受非即時 → locate(記得先 updatedb)
  3. 確認系統指令的安裝路徑/文件/原始碼 → whereis
  4. 確認當前環境下執行的是哪個指令 → which
  5. 判斷指令是內建還是外部程式 → type

進階技巧:find + xargs/parallel 處理大量檔案

# 安全處理含空白/特殊字元的檔名
find . -name '*.tmp' -print0 | xargs -0 rm -f

# 並行加速刪除
find /var/log -name '*.log' -mtime +30 -print0 | parallel -0 rm -f

總結

掌握五大工具的分工與組合,能讓您在茫茫檔案系統中如魚得水。日常運維建議:locate 找大方向,find 精準定位並處理,which/type 驗證執行環境。

copyright © 萬盛學電腦網 all rights reserved