Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 五大檔案搜尋指令詳解:find、locate、whereis、which、type

編輯:Linux 教學

Linux 提供多種檔案搜尋工具,各有適用場景與效能特性。本文系統整理 find、locate、whereis、which、type 五大指令的語法、參數與實戰範例,助你精準選擇最高效的搜尋方式。

1. find — 最強大、即時遍歷檔案系統

語法:find [路徑] [條件] [動作]

  • 路徑:預設為當前目錄(.),遞迴搜尋所有子目錄。
  • 條件:如 -name、-type、-size、-mtime、-user 等。
  • 動作:-print(預設)、-ls、-exec cmd {} \;、-delete 等。

常用範例

# 搜尋當前目錄下所有以 my 開頭的檔案
find . -name 'my*'

# 顯示詳細資訊(inode、權限、大小、時間)
find . -name 'my*' -ls

# 搜尋 10 分鐘內修改過的一般檔案(不含目錄、特殊檔)
find . -type f -mmin -10

# 搜尋超過 100MB 的檔案並刪除(謹慎使用)
find /var/log -type f -size +100M -delete

# 組合條件:找出屬於用戶 www、最近 7 天修改、副檔名 .log 的檔案
find /home/www -user www -mtime -7 -name '*.log'

2. locate — 秒級搜尋,基於預建資料庫

原理:讀取 /var/lib/mlocate/mlocate.db(或 /var/lib/locatedb),由 updatedb 每日自動更新。

優缺點:極快,但無法找到最新建立/變更的檔案;需手動執行 updatedb 更新資料庫。

locate /etc/sh          # 找 /etc 下所有 sh 開頭的檔
locate ~/m              # 家目錄下 m 開頭的檔
locate -i ~/m           # 忽略大小寫
updatedb                # 手動更新資料庫

3. whereis — 專門定位二進制、原始碼、手冊頁

參數:-b(二進制)、-m(man page)、-s(原始碼)。省略參數則全部顯示。

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

4. which — 在 PATH 中尋找命令實際路徑

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

which grep
# /usr/bin/grep

5. type — 判斷命令類型(內建/別名/外部)

type cd
# cd is a shell builtin

type grep
# grep is /usr/bin/grep

type -p grep   # 相當於 which grep
# /usr/bin/grep

選擇指南

需求推薦指令
即時、複雜條件、需對結果處理find
快速定位已知檔名、不介意稍舊資料locate
確認命令二進制/man/源碼位置whereis
驗證 PATH 中實際執行的命令版本which
區分 shell 內建、別名、外部命令type

熟練組合使用這五大工具,能在系統管理、腳本編寫、問題排查中事半功倍。

Copyright © Windows教程網 All Rights Reserved