Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux基礎知識

Linux 命令與文件搜尋:which、whereis、locate 與 find

總有些命令或文件會偶爾想不起來在哪裡。下面這幾個工具能幫你迅速定位。

一、搜尋命令:which

功能:在 PATH 所配置的目錄中搜尋可執行命令。

which [-a] command
-a  列出所有匹配結果,而非只顯示第一個

Linux 命令與文件搜尋:which、whereis、locate 與 find

Linux 命令與文件搜尋:which、whereis、locate 與 find

上面兩張圖對比可看出有無 -a 的差別。

注意:which 只沿 PATH 配置的路徑查找,且需接完整命令名。Shell 內建命令(如 cd、echo)用 which 是查不出來的,需用 type 或 command -v。

二、搜尋文件或目錄名:whereis

功能:在特定的系統目錄中搜尋文件或目錄。

whereis [-blmsu] 文件或目錄名
-b  只找 binary 文件
-l  列出所有查詢過的目錄
-m  只在 manual 說明檔中查找
-s  只找 source 來源文件
-u  搜尋不在 bms 分類中的其他特殊文件

Linux 命令與文件搜尋:which、whereis、locate 與 find

Linux 命令與文件搜尋:which、whereis、locate 與 find

注意:whereis 後面需接完整的文件或目錄名,不支援模糊匹配。

三、從資料庫搜尋:locate

功能:在預先建立的資料庫中查找文件或目錄,速度極快。

locate -[iclSr] 部分檔案名
-i  忽略大小寫
-c  不輸出文件名,只計算數量
-l  限制輸出行數,如 -l 3
-S  顯示 locate 所用資料庫的詳細資訊
-r  後接正則表達式

Linux 命令與文件搜尋:which、whereis、locate 與 find

Linux 命令與文件搜尋:which、whereis、locate 與 find

注意:locate 依賴資料庫,而資料庫通常每天才自動更新一次(各發行版不同),因此剛建立的文件可能查不到。可手動執行 updatedb 更新——它會讀取 /etc/updatedb.conf 的設定,掃描硬盤後重建索引。

四、功能最強的 find

find [path] [option] [action]

時間相關

-mtime n    n 天以內修改過內容的文件
-mtime +n   超過 n 天之前修改過的文件
-mtime -n   n 天(含)之內修改過的文件
-newer file 比指定文件更新的文件

Linux 命令與文件搜尋:which、whereis、locate 與 find

Linux 命令與文件搜尋:which、whereis、locate 與 find

用戶與群組相關

-uid n / -gid n    依 user ID / group ID 搜尋
-user name / -group name  依帳戶名 / 組名搜尋
-nouser    擁有者不在 /etc/passwd 中的文件
-nogroup   群組不在 /etc/group 中的文件

Linux 命令與文件搜尋:which、whereis、locate 與 find

Linux 命令與文件搜尋:which、whereis、locate 與 find

權限與名稱相關

-name filename      檔名為 filename
-size [+-]SIZE      比 SIZE 大(+)或小(-),單位 c 為 byte、k 為 kbyte
-type TYPE          f 一般文件、b/c 設備、d 目錄、l 連結、s socket、p FIFO
-perm mode          權限恰好等於 mode
-perm -mode         權限必須完整包含 mode
-perm /mode         權限包含 mode 中任一項即可

Linux 命令與文件搜尋:which、whereis、locate 與 find

Linux 命令與文件搜尋:which、whereis、locate 與 find

Linux 命令與文件搜尋:which、whereis、locate 與 find

Linux 命令與文件搜尋:which、whereis、locate 與 find

Linux 命令與文件搜尋:which、whereis、locate 與 find

實務上的選擇邏輯很簡單:路徑明確、按屬性精確篩選用 find;只知道大概位置且追求速度用 locate;查可執行命令用 which。

Copyright © Linux教程網 All Rights Reserved