Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

Linux find 指令詳解:從 which、whereis、locate 到 find 全解析

一、搜尋指令概論

「這個檔案到底放哪?」是每個 Linux 使用者都會遇到的問題。常見的搜尋工具有 which、whereis、locate、find 四支。其中 whereis 與 locate 走的是資料庫路線,因此速度飛快,但代價是結果可能不是即時的。

二、which:找可執行檔

依據 PATH 環境變數所規範的路徑去搜尋可執行檔;加上 -a 可列出所有同名執行檔。

which 可執行檔名
which -a 可執行檔名

例:列出 ls 的位置

[root@chris ~]# which -a ls
alias ls='ls --color=tty'
/bin/ls

三、whereis:查資料庫找特定檔案

系統會把檔案位置記錄在資料庫中,每天由 updatedb 更新(也可手動執行 /usr/bin/updatedb)。

whereis [-bmsu] 檔案或目錄名
-b   只找二進位檔
-m   只找 man 說明檔路徑下的檔案
-s   只找原始碼
-u   找沒有說明檔的檔案

例:查找含 passwd 的檔案

Linux find 指令詳解:從 which、whereis、locate 到 find 全解析

四、locate:同樣走資料庫

輸出的是資料庫中已同步的資訊,並非即時掃描結果。搜尋範圍可在 /etc/updatedb.conf 中調整。

locate 檔名或部分檔名
Linux find 指令詳解:從 which、whereis、locate 到 find 全解析

五、find:即時、精準、可遍歷

find 會即時遍歷指定目錄下的所有檔案,速度較慢但條件表達力最強。

find 搜尋路徑 搜尋標準 找到的處理動作

三個部分都有預設值:路徑預設為當前目錄,標準預設為全部檔案,動作預設為顯示到螢幕。

依檔名匹配

-name 'FILENAME'    精確匹配檔名
-iname 'FILENAME'   忽略大小寫
Linux find 指令詳解:從 which、whereis、locate 到 find 全解析 Linux find 指令詳解:從 which、whereis、locate 到 find 全解析

依屬主與屬組匹配

-user USERNAME     # 屬主
-group GROUPNAME   # 屬組
-uid UID           # 依 UID
-gid GID           # 依 GID
-nouser            # 沒有屬主的檔案
-nogroup           # 沒有屬組的檔案

例:find /tmp -gid 2012

依檔案類型匹配

-type f   普通檔案
-type d   目錄
-type p   命名管道
-type s   ソケット
-type l   符號連結
Linux find 指令詳解:從 which、whereis、locate 到 find 全解析

依大小匹配

-size +#K   大於 # KB
-size -#M   小於 # MB
-size #G    等於 # GB

組合條件

-a     AND(多條件之間的預設關係)
-o     OR
-not   NOT

優先序:-not > -a > -o

例:

find /tmp -not -type d
find /tmp -not \( -type d -o -type s \)

依時間戳匹配

-mtime  修改時間
-atime  存取時間
-ctime  變更時間
(若要以分鐘為單位,改用 -mmin / -amin / -cmin)

#    正好是 # 天那一天的時間
-#   # 天之內
+#   至少 # 天

依權限匹配

-perm mode    精確匹配權限
-perm /mode   三位中任一符合即可
-perm -mode   權限必須完全涵蓋 mode
Linux find 指令詳解:從 which、whereis、locate 到 find 全解析

例:找出 /etc 下所有使用者都沒有寫權限的檔案並顯示詳細資訊

Linux find 指令詳解:從 which、whereis、locate 到 find 全解析

對結果執行動作

-print              預設,印到螢幕
-ls                 以 ls -l 的格式列出詳細資訊
-ok COMMAND {} \;   每個操作都需使用者確認
-exec COMMAND {} \; 直接執行,不需確認

兩者都必須以 \; 結尾,{} 代表匹配到的檔案。

例:把所屬組有寫權限的檔案改名加上 .new 後綴

find ./ -perm -020 -exec mv {} {}.new \;

六、腳本練習

需求:撰寫一支腳本,顯示系統上 shell 為指定類型的帳號並統計人數。-s 後的參數必須存在於 /etc/shells 中,否則不執行;另需支援 --help。

#!/bin/bash
#
if [ $1 == '-s' ]; then
  ! grep "${2}$" /etc/shells &> /dev/null && echo "Invalid shell." && exit 7
elif [ $1 == '--help' ]; then
  echo "Usage: showshells.sh -s SHELL | --help"
  exit 0
else
  echo "Unknown Options."
  exit 8
fi

NUMOFUSER=`grep "${2}$" /etc/passwd | wc -l`
SHELLUSERS=`grep "${2}$" /etc/passwd | cut -d: -f1`
SHELLUSERS=`echo $SHELLUSERS | sed 's@[[:space:]]@,@g'`
echo -e "$2, $NUMOFUSER users, they are: \n$SHELLUSERS"

本文出自「Chris—on the way」部落格,請務必保留此出處 https://chrinux.blog.51cto.com/6466723/1153802

Copyright © Linux教程網 All Rights Reserved