Computer >> Hướng Dẫn Máy Tính >  >> Điện Thoại Thông Minh >> Linux

Hướng dẫn bắt đầu dùng lệnh find trong Linux (với ví dụ thực tế)

Hướng dẫn find – công cụ tìm kiếm file/thư mục mạnh mẽ, linh hoạt, chuẩn POSIX, có sẵn mọi Linux/Unix.

Cú pháp cơ bản

find [đường_dẫn_tìm_kiếm] [biểu_thức_điều_kiện] [hành_động]
  • Tất cả tham số tùy chọn. find đơn độc = liệt kê mọi thứ từ thư mục hiện tại đệ quy.

Ví dụ phổ biến

Tìm theo tên

# find -name "*.txt"                    # Hiện tại, đệ quy
# find /home/hobbes /home/calvin -name "*.txt"  # Nhiều thư mục
# find /home/calvin -iname "picasso"    # Không phân biệt hoa/thường (-iname)

Loại bỏ lỗi "Permission denied"

# find /home -name "*.txt" 2>/dev/null

Tìm theo thời gian (Time-based)

Tuỳ chọnĐơn vịVí dụ
-mtimeNgày (24h)-mtime -7 (7 ngày qua), -mtime +30 (trước 30 ngày)
-mminPhút-mmin -45 (45 phút qua), -mmin +15 -mmin -25 (15-25 phút trước)
-atimeNgày truy cập cuối
-ctimeNgày thay đổi metadata

Kiểm soát độ sâu (Depth)

# find /home/calvin -maxdepth 2 -name "*.txt"   # Chỉ 2 cấp đầu
# find /home/calvin -mindepth 2 -name "*.txt"   # Bỏ qua 1 cấp đầu

Tìm theo kích thước

# find /home -size +100M -type f    # File > 100MB
# find /var/log -size +50M -type f  # Log file lớn
  • Đơn vị: c (byte), k (KiB), M (MiB), G (GiB).
  • + = lớn hơn, - = nhỏ hơn, không dấu = chính xác.

Tìm theo loại

# find . -type f    # File thường
# find . -type d    # Thư mục
# find . -type l    # Symlink
# find . -type b/c/p/s  # Block/Char device, Pipe, Socket

Tìm theo quyền/owner

# find / -perm /4000 -type f 2>/dev/null  # File SUID (root exploit check)
# find /home -user calvin -type f
# find / -group developers -type f

Hành động (Actions)

# find . -name "*.log" -delete                 # Xóa trực tiếp (cẩn thận!)
# find . -name "*.tmp" -exec rm -f {} +        # Xóa qua exec (an toàn hơn)
# find . -name "*.jpg" -exec cp {} /backup \;
# find . -type f -printf "%p %s %TY-%Tm-%Td\n" # In tùy chỉnh: path size mtime

Kết hợp find + xargs / -exec (Hiệu năng)

  • -exec cmd {} +: Gom nhiều file → 1 lệnh (nhanh, built-in).
  • -exec cmd {} \;: 1 lệnh/file (chậm).
  • find ... -print0 | xargs -0 cmd: Chuẩn POSIX, an toàn tên file đặc biệt.

Lưu output ra file

# find /home/calvin -name "*.txt" > /tmp/search.log

Mẹo pro

  • find / -xdev -type f -size +100M -printf '%s %p\n' | sort -nr | head: Top file lớn nhất hệ thống (bỏ qua mount).
  • find . -type f -name "*.py" -exec grep -l "TODO" {} +: Tìm file Python chứa TODO.
  • find . -empty -type d -delete: Xóa thư mục rỗng đệ quy.