萬盛學電腦網

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

Linux 文件搜索命令大全:find、locate、whereis、which、type

核心命令對比

命令搜索範圍速度適用場景
find實時遍歷目錄樹慢精確查找、複雜條件 (時間、大小、權限、類型)、執行動作
locate預建數據庫 (/var/lib/mlocate.db)極快按名稱快速定位、全盤搜索、不需實時性
whereis特定目錄 (二進制/手冊/源碼)快定位命令二進制、man 頁、源碼路徑
whichPATH 環境變量目錄極快確認命令實際執行路徑、別名覆蓋排查
typeShell 內部/外部命令極快區分內建命令與外部可執行文件、顯示別名定義

find 詳解

基本語法

find   

常用條件

選項說明示例
-name pattern文件名匹配 (支持 * ?)find . -name "*.log"
-iname pattern忽略大小寫find . -iname "readme*"
-type f/d/l/c/b/p/s文件類型 (普通/目錄/符號鏈接/字符/塊/管道/Socket)find /tmp -type f
-size n[c/k/M/G]文件大小 (+大於 -小於)find /var/log -size +100M
-mtime n修改時間 (天) (+n 天前, -n 天內)find . -mtime -7
-mmin n修改時間 (分鐘)find . -mmin -10
-user name屬主用戶find /home -user www
-perm mode權限匹配find / -perm 644
-newer file比參考文件新find . -newer stamp.txt

常用動作

  • -print:默認打印路徑
  • -ls:詳細屬性 (類似 ls -l)
  • -exec cmd {} \;:對每個結果執行命令
  • -ok cmd {} \;:執行前確認
  • -delete:刪除 (謹慎!)

經典範例

# 1. 查找全盤 httpd.conf
find / -name httpd.conf -print

# 2. 模糊查找含 http 的文件
find / -name "*http*" -print

# 3. 查找 /etc 下小於 2500 字節的文件
find /etc -size -2500c -print

# 4. 最近 10 分鐘修改過的普通文件
find . -type f -mmin -10

# 5. 刪除 30 天前的 .tmp 文件 (極度小心)
find /tmp -name "*.tmp" -mtime +30 -delete

locate 詳解

  • 數據庫每日自動更新 (/etc/cron.daily/mlocate),手動更新:updatedb
  • locate /etc/sh:/etc 下以 sh 開頭
  • locate -i ~/m:忽略大小寫搜索家目錄下 m 開頭

whereis / which / type 速查

whereis grep      # 二進制、man、源碼路徑
which grep        # PATH 中第一個 grep 路徑
type cd           # cd is a shell builtin
type -p grep      # 等同 which grep
type -a ls        # 顯示所有同名命令 (別名、函數、文件)

最佳實踐建議

  • 知道大概路徑用 find,全盤模糊名用 locate (先 updatedb)。
  • 確認命令路徑用 which 或 type -p。
  • 腳本中優先用 command -v (POSIX 標準) 判斷命令存在性。
  • find 配合 -exec + 批量處理比 xargs 更安全處理特殊文件名。
copyright © 萬盛學電腦網 all rights reserved