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

Linux find 指令完整用法與常用條件整理

Linux 是「一切皆檔案」的系統,不靠副檔名辨識檔案類型。find 指令若不指定搜尋目錄,預設會對整個系統進行搜尋。

一、命令格式

find pathname -options [-print -exec -ok ...]

pathname:搜尋的起始目錄,. 代表目前目錄,/ 代表根目錄。

root@ubuntu:~# find /root
/root
/root/file
/root/Test2.txt
...

-print:把符合條件的結果輸出到標準輸出(系統預設行為)。

-exec command {} \;:對每個符合的檔案執行指定的 shell 命令。

root@ubuntu:~# find /root -type f -exec ls -l {} \;
-rw-r--r-- 1 root root 1490 May 16 05:08 /root/file
-rw-r--r-- 1 root root  226 May 16 06:40 /root/cmd
-rw-r--r-- 1 root root    0 May 20 18:57 /root/Test2.txt

-ok command {} \;:與 -exec 相同,但執行前會先詢問確認,安全性更高。

二、常用條件

-name:依檔名搜尋(精確比對);-iname:不區分大小寫。

root@ubuntu:~# find /root -name Test.txt
/root/Test.txt
root@ubuntu:~# find /root -iname test.txt
/root/Test.txt

-perm:依權限搜尋。給定數字如 644 為精確比對;-perm +權限 表示任一類使用者具備該權限即符合;-perm -權限 表示所有類別使用者都必須具備該權限。

root@ubuntu:~# find /root -perm 644
/root/Test2.txt

-user / -group:依檔案所有者與所屬組搜尋。

root@ubuntu:~# find /root -user root

-mtime -n / +n:依內容修改時間搜尋,-n 為 n 天以內,+n 為 n 天以前。

root@ubuntu:~# find /root -mtime +2
/root/file

-nouser / -nogroup:檔案所有者在 /etc/passwd 中不存在,或所屬組在 /etc/group 中不存在。

-type:依檔案類型搜尋。b 區塊裝置、d 目錄、c 字元裝置、p 管道、l 符號連結、f 一般檔案。

-size n [c]:搜尋長度為 n 個區塊的檔案,加上 c 則以位元組計算;-size +n 或 -size -n 表示大於或小於 n。

-depth:先搜尋目前目錄的檔案,再進入子目錄。

-fstype:搜尋位於指定類型檔案系統中的檔案,類型通常可在 /etc/fstab 中找到。

-mount:搜尋時不跨越檔案系統的掛載點。

-follow:遇到符號連結時追蹤至連結指向的檔案。

-cpio:對符合的檔案使用 cpio 指令備份到磁帶裝置。

實務上最常用的一句話莫過於 find /path -type f -name "*.log" -mtime -7:找出某目錄下七天內修改過的日誌檔。

Copyright © Linux教程網 All Rights Reserved