找不到指令或檔案時別著急,Linux 提供了 which、whereis、locate、find 這四把利器,各有擅長的場景。搞懂它們的差異,搜尋效率立刻翻倍。
which 用來找出 PATH 環境變數中包含的可執行檔(也就是指令):
which [-a] command
-a:列出所有符合的指令
whereis 與 locate 是從資料庫中查詢,因此速度飛快,但缺點是無法找到最新的資料,因為資料庫預設每天才更新一次(也可手動執行 updatedb 更新)。
whereis file/dirname
locate [-i] keyword(-i 表示忽略大小寫)
兩者的差別在於:whereis 是精準比對,而 locate 是關鍵字比對。
find 則是直接在硬碟上搜尋,速度較慢,但功能最強大:
find [PATH] [option] [action]
[PATH] 指定搜尋路徑,[option] 指定條件,例如:
-name 欲查找的檔名
-atime -ctime -mtime 檔案時間
-type 檔案類型
-size 檔案大小
其中與時間相關的參數特別實用:
-mtime +n:列出 n 天前(不含 n)被修改過的檔案
-mtime -n:列出 n 天內(含 n)被修改過的檔案
-newer file:列出比 file 還新的檔案
[action] 代表對搜尋結果執行的操作,內容以 -exec 開頭、以 \; 結束,例如:
find /etc -name sysconfig -exec ls -l {} \;
其中 {} 代表 find 找到的每一筆內容,因此這條指令會找出 /etc 下的 sysconfig 檔案與目錄,並列出其詳細結構。