Bash/Zsh Bash/Zsh Mastering the Find Command in Bash

Mastering the Find Command in Bash

AS
Aman Saurav
| Dec 25, 2024 |
read
#bash #find #search #file-management

Mastering the Find Command in Bash

The find command is one of the most powerful tools in the Unix/Linux arsenal for searching files and directories. Unlike simple search tools, find can filter by name, type, size, modification time, permissions, and execute commands on the results.

Basic Syntax

find [path] [options] [expression]

Simple Examples

Find by Name

# Find all .txt files in current directory and subdirectories
find . -name "*.txt"

# Case-insensitive search
find . -iname "*.TXT"

# Find exact filename
find /home -name "config.json"

Find by Type

# Find only directories
find . -type d

# Find only files
find . -type f

# Find symbolic links
find . -type l

Advanced Filtering

By Size

# Files larger than 100MB
find . -type f -size +100M

# Files smaller than 1KB
find . -type f -size -1k

# Files exactly 50MB
find . -type f -size 50M

Size units:

  • c - bytes
  • k - kilobytes
  • M - megabytes
  • G - gigabytes

By Modification Time

# Modified in last 7 days
find . -type f -mtime -7

# Modified more than 30 days ago
find . -type f -mtime +30

# Modified exactly 10 days ago
find . -type f -mtime 10

# Modified in last 24 hours
find . -type f -mtime -1

By Permissions

# Find files with 777 permissions
find . -type f -perm 0777

# Find files readable by everyone
find . -type f -perm -444

# Find directories with write permission for group
find . -type d -perm -020

Combining Conditions

AND Logic (default)

# Find .log files larger than 10MB
find . -name "*.log" -size +10M

# Find files modified in last week AND larger than 1MB
find . -type f -mtime -7 -size +1M

OR Logic

# Find .txt OR .md files
find . -name "*.txt" -o -name "*.md"

# Find files larger than 100M OR older than 30 days
find . -type f \( -size +100M -o -mtime +30 \)

NOT Logic

# Find all files EXCEPT .txt files
find . -type f ! -name "*.txt"

# Find directories NOT named node_modules
find . -type d ! -name "node_modules"

Executing Commands on Results

Using -exec

# Delete all .tmp files
find . -name "*.tmp" -exec rm {} \;

# Change permissions of all .sh files
find . -name "*.sh" -exec chmod +x {} \;

# Copy all .jpg files to backup directory
find . -name "*.jpg" -exec cp {} /backup/ \;

Syntax explanation:

  • {} - placeholder for found file
  • \; - end of -exec command

Using -exec with Confirmation

# Delete with confirmation
find . -name "*.bak" -ok rm {} \;

More Efficient: -exec with +

# Pass multiple files at once (faster)
find . -name "*.txt" -exec grep "error" {} +

Practical Real-World Examples

1. Find and Delete Empty Files

#!/bin/bash
# Find and remove empty files
find . -type f -empty -delete

# Or with confirmation
find . -type f -empty -ok rm {} \;

2. Find Large Files (Disk Space Audit)

#!/bin/bash
# Find top 10 largest files
find . -type f -exec du -h {} + | sort -rh | head -10

3. Find Recently Modified Files

#!/bin/bash
# Find files modified in last hour
find /var/log -type f -mmin -60

# Find files modified today
find . -type f -newermt "$(date +%Y-%m-%d)"

4. Clean Old Log Files

#!/bin/bash
# Delete log files older than 30 days
find /var/log -name "*.log" -type f -mtime +30 -delete

# Or compress them instead
find /var/log -name "*.log" -type f -mtime +30 -exec gzip {} \;

5. Find Duplicate Filenames

#!/bin/bash
# Find files with same name in different directories
find . -type f -printf '%f\n' | sort | uniq -d

6. Find and Archive

#!/bin/bash
# Find all .pdf files and create archive
find . -name "*.pdf" -type f -print0 | tar -czvf pdfs.tar.gz --null -T -

7. Find Files by Owner

# Find files owned by specific user
find /home -user john -type f

# Find files owned by specific group
find /var/www -group www-data
# Find and list broken symlinks
find . -type l ! -exec test -e {} \; -print

# Find and delete broken symlinks
find . -type l ! -exec test -e {} \; -delete

Optimizing Find Performance

1. Limit Search Depth

# Search only 2 levels deep
find . -maxdepth 2 -name "*.txt"

# Search at least 3 levels deep
find . -mindepth 3 -name "*.log"

2. Prune Directories

# Skip .git directories
find . -path "*/.git" -prune -o -name "*.js" -print

# Skip multiple directories
find . \( -path "*/node_modules" -o -path "*/.git" \) -prune -o -type f -print

3. Use -print0 with xargs

# Handle filenames with spaces safely
find . -name "*.txt" -print0 | xargs -0 grep "error"

# Parallel processing with xargs
find . -name "*.jpg" -print0 | xargs -0 -P 4 -I {} convert {} {}.png

Find vs Other Tools

CommandBest ForSpeed
findComplex searches, execute actionsMedium
locateQuick filename searchesVery Fast
grep -rContent searchingSlow
fd (modern alternative)User-friendly syntaxFast

Common Pitfalls

❌ Don’t: Forget to quote patterns

# BAD - shell expands * before find sees it
find . -name *.txt

# GOOD - find receives the pattern
find . -name "*.txt"

❌ Don’t: Use -exec inefficiently

# BAD - spawns new process for each file
find . -name "*.txt" -exec cat {} \;

# GOOD - passes multiple files at once
find . -name "*.txt" -exec cat {} +

✅ Do: Handle spaces in filenames

# Use -print0 with xargs -0
find . -name "*.mp3" -print0 | xargs -0 -I {} cp {} /music/

Download Sample Scripts

📦 Download Find Command Examples (ZIP)

The ZIP includes:

  • find_basics.sh - Basic find examples
  • cleanup_script.sh - Automated cleanup using find
  • backup_finder.sh - Find and backup specific files
  • disk_audit.sh - Find large files and directories
  • sample_directory/ - Test directory structure
  • README.md - Usage guide

Video Tutorial

Quick Reference Cheat Sheet

# By name
find . -name "pattern"          # Case-sensitive
find . -iname "pattern"         # Case-insensitive

# By type
find . -type f                  # Files
find . -type d                  # Directories
find . -type l                  # Symlinks

# By size
find . -size +100M              # Larger than 100MB
find . -size -1k                # Smaller than 1KB

# By time
find . -mtime -7                # Modified last 7 days
find . -mmin -60                # Modified last 60 minutes

# Actions
find . -name "*.tmp" -delete    # Delete matches
find . -name "*.sh" -exec chmod +x {} \;  # Execute command

# Combinations
find . -name "*.log" -size +10M -mtime +30  # AND
find . -name "*.txt" -o -name "*.md"        # OR
find . -type f ! -name "*.bak"              # NOT

Summary

The find command is essential for:

  • ✅ Searching files by multiple criteria
  • ✅ Automating file management tasks
  • ✅ Cleaning up disk space
  • ✅ Building complex file processing pipelines

Master find and you’ll have precise control over your filesystem!


Download Exercise Files

Get the source code, datasets, and cheat sheet for this lesson.

Download Resources