Linux 提供多種檔案搜尋工具,各有適用場景與效能特性。本文系統整理 find、locate、whereis、which、type 五大指令的語法、參數與實戰範例,助你精準選擇最高效的搜尋方式。
語法: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'
原理:讀取 /var/lib/mlocate/mlocate.db(或 /var/lib/locatedb),由 updatedb 每日自動更新。
優缺點:極快,但無法找到最新建立/變更的檔案;需手動執行 updatedb 更新資料庫。
locate /etc/sh # 找 /etc 下所有 sh 開頭的檔
locate ~/m # 家目錄下 m 開頭的檔
locate -i ~/m # 忽略大小寫
updatedb # 手動更新資料庫
參數:-b(二進制)、-m(man page)、-s(原始碼)。省略參數則全部顯示。
whereis grep
# 輸出:grep: /usr/bin/grep /usr/share/man/man1/grep.1.gz
回傳 $PATH 中第一個匹配的可執行檔路徑,適合確認「執行的是哪個版本」。
which grep
# /usr/bin/grep
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 |
熟練組合使用這五大工具,能在系統管理、腳本編寫、問題排查中事半功倍。