天天看點

Linux中which,whereis,locate和find的差別locate

linux中對檔案進行查找主要使用的就是标題中的四個指令,為什麼會提供四個指令,當然是因為他們彼此功能上存在差異,下面就簡單介紹一下這四個指令的特點.

which

which returns the pathnames of the files (or links) which would be executed in the current environment, had its arguments been given as  commands  in a strictly POSIX-conformant shell.  It does this by searching
the PATH for executable files matching the names of the  arguments.  It does not follow symbolic links.
           

從上面的說明我們可以知道,which隻查找目前使用者PATH環境變量(可以通過echo $PATH檢視)下的可執行檔案,這樣的話範圍就比較窄,當然速度也是飛起.

whereis

whereis locates the binary, source and manual files for  the  specified command  names.  The supplied names are first stripped of leading pathname components and any (single) trailing extension of  the  form  .ext(for  example:  .c)  Prefixes  of s.  resulting from use of source code control are also dealt with.   whereis  then  attempts  to  locate  the desired  program in the standard Linux places, and in the places specified by $PATH and $MANPATH.
           

whereis指令隻能用于程式名的搜尋,而且隻搜尋二進制檔案(參數-b)、man說明檔案(參數-m)和源代碼檔案(參數-s)。如果省略參數,則傳回所有資訊。

和find相比,whereis查找的速度非常快,這是因為linux系統會将 系統内的所有檔案都記錄在一個資料庫檔案中,當使用whereis和下面即将介紹的locate時,會從資料庫中查找資料,而不是像find指令那樣,通 過周遊硬碟來查找,效率自然會很高。

但是該資料庫檔案并不是實時更新,預設情況下時一星期更新一次,是以,我們在用whereis和locate 查找檔案時,有時會找到已經被删除的資料,或者剛剛建立檔案,卻無法查找到,原因就是因為資料庫檔案沒有被更新。

locate

locate檔案用于查找檔案(包括普通檔案),他與全盤搜尋的find指令的差別是locate依賴于一個已經建好的并且每天進行更新的資料庫.這樣的話也會存在whereis存在的問題,就是資料庫可能不是最新的,會缺少檔案或者存在已經被删除的檔案.但是它帶來的确實速度上的大幅度提升,大家自己去感受一下就知道了.locate支援正規表達式比對

當然我們也可以手動去更新這個資料庫,隻要在任意目錄下運作sudo updatedb指令即可.

find

這個指令就像我們在windows下面的搜尋了,進行的是在指定目錄下的掃描,速度會稍微慢一點.

find可用的參數非常多,支援正規表達式比對.

如果我們不知道要找的檔案在那個目錄下,那就用根目錄/去找吧,如:

上面的指令意思是在全局中查找名字為filename的檔案或者檔案名,找到之後print出來

繼續閱讀