Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux find 指令進階練習:複合條件查詢實戰十則

編輯:Linux 系統常見問題解答

find 的威力在於複合條件邏輯組合。本文整理十個實戰練習,涵蓋擁有者、權限、時間、大小、類型等多維度查詢,助您熟練掌握「精準找檔」技巧。

練習環境假設

  • 測試帳號:root、bin、hadoop、bash、rainman (UID 507)
  • 目標目錄:/var、/usr、/etc、/

十大實戰範例

  1. /var 下屬主 root 且屬組 mail 的所有檔
    find /var \( -user root -a -group mail \) -ls
    # 結果:/var/spool/mail
  2. /usr 下不屬於 root、bin、hadoop 的檔
    find /usr ! \( -user root -o -user bin -o -user hadoop \) -exec ls -l {} \;
    # 結果:/usr/libexec/abrt-action-install-debuginfo-to-abrt-cache (屬 abrt)
  3. /etc 下一週內修改過、且屬主非 root/hadoop 的檔
    find /etc ! \( -user root -o -user hadoop \) -mtime -7 -exec ls -l {} \;
    # 結果:/etc/find_lab/find.txt (屬 bash)
  4. 全系統無擁有者/群組、且一週內被存取過的檔
    find / -atime -7 \( -nouser -o -nogroup \) -ls
    # 發現 rainman 相關檔案、/lab/readme.txt 等(含 /proc 錯誤可忽略)
  5. /etc 下大於 20KB 的一般檔案
    find /etc -type f -size +20k -exec ls -l {} \; | head -n 10
    # 列出 httpd.conf、dnsmasq.conf、gimp gimprc 等大型設定檔
  6. 找出 /home 下最近 30 天未存取的大檔(清理候選)
    find /home -type f -size +50M -atime +30 -ls
  7. 找擁有 SUID/SGID 權限的可執行檔(安全稽核)
    find / -type f \( -perm -4000 -o -perm -2000 \) -exec ls -l {} \;
  8. 依修改時間排序顯示 /var/log 下前 10 大檔
    find /var/log -type f -exec ls -lt {} + | head -n 10
  9. 刪除 /tmp 下 7 天前、非 root 擁有的暫存檔
    find /tmp -type f -mtime +7 ! -user root -delete
  10. 找出系統中所有斷掉的符號連結
    find / -xtype l -ls
    # 或 find / -type l ! -exec test -e {} \; -print

關鍵語法重點

  • () 分組、-a AND、-o OR、! NOT(需轉義 \( \))
  • -exec cmd {} \; 單檔執行;-exec cmd {} + 批次執行(效率較高)
  • -ls 等同 -exec ls -dils {} \;,快速看詳細資訊
  • 時間參數:-mtime n(n*24h 前修改)、-mtime -n(n*24h 內)、-mtime +n(超過 n*24h)

熟練這十類組合,應付 90% 的檔案稽核、清理、遷移需求綽綽有餘。

Copyright © Windows教程網 All Rights Reserved