---
title: "Find"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/find
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# Find

Complete find reference with file searching, filtering by type/size/time, permissions, advanced operations, and practical examples for locating files

8 Categories25 Sections54 ExamplesPublished: 01 Jan 2023Updated: 28 Feb 2025

FindFile SearchDiscoveryFile OperationsLinuxShell

[Markdown for AI(opens in a new tab)](/find/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Linux & System Administration](/series/linux--system-administration)6/12

[PreviousCurl](/cheatsheets/curl)[NextGrep](/cheatsheets/grep)

All posts in this series (12)

Cheatsheets12

1.  [AWK](/cheatsheets/awk)
2.  [Bash](/cheatsheets/bash)
3.  [Chmod](/cheatsheets/chmod)
4.  [Cron](/cheatsheets/cron)
5.  [Curl](/cheatsheets/curl)
6.  [FindYou are here](/cheatsheets/find)
7.  [Grep](/cheatsheets/grep)
8.  [Netcat](/cheatsheets/nc)
9.  [Netstat](/cheatsheets/netstat)
10.  [Sed](/cheatsheets/sed)
11.  [SSH](/cheatsheets/ssh)
12.  [Linux Networking](/cheatsheets/linux-networking)

## [Best practices for find command usage](#best-practices-for-find-command-usage)

-   **Always quote patterns** to prevent shell expansion of special characters
-   **Use -type f first** in find expressions for optimal performance
-   **Prune heavy directories early** like node\_modules, .git, .venv
-   **Use -maxdepth** to limit search depth and improve performance
-   **Test commands first** with -ls or -printf before using -delete
-   **Use + instead of ;** with exec for better performance on many files
-   **Suppress permission errors** with 2>/dev/null for cleaner output
-   **Combine multiple criteria** to create efficient targeted searches
-   **Use -xdev** to skip other filesystems when needed
-   **Consider locate command** for quick name-only searches (faster than find)

## [Common errors and solutions](#common-errors-and-solutions)

-   **error: “Permission denied”** → Use 2>/dev/null to suppress or run with sudo
-   **error: “No such file or directory”** → Verify path exists and is readable
-   **error: “Unexpected operator or missing operand”** → Check parentheses are escaped: \\( \\)
-   **error: “Syntax error near token”** → Verify \\; or + is present after -exec
-   **error: “Find is too slow”** → Use -maxdepth, -prune, and -type filters
-   **error: “Deleted wrong files accidentally”** → Always preview with find first!
-   **error: “Pattern not matching expected files”** → Test pattern with -ls before -delete
-   **error: “xtype/executable not recognized”** → Use newer GNU find; some options are GNU-specific

* * *

ref: [https://man7.org/linux/man-pages/man1/find.1.html](https://man7.org/linux/man-pages/man1/find.1.html)

[Getting Started](#category-getting-started)

-   [What is Find](#section-what-is-find)
-   [Installation and Setup](#section-installation-setup)

[Basic Search](#category-basic-search)

-   [Simple Name Search](#section-simple-name-search)
-   [Case-Insensitive Search](#section-case-insensitive-search)
-   [Path Matching](#section-path-matching)
-   [Type Matching](#section-type-matching)

[File Size & Type](#category-file-size-type)

-   [Size Filtering](#section-size-filtering)
-   [File Type Tests](#section-file-type-tests)
-   [Empty Files](#section-empty-files)

[Time-Based Search](#category-time-based-search)

-   [Modification Time](#section-modification-time)
-   [Access Time](#section-access-time)
-   [Change Time](#section-change-time)
-   [Minute-Based Searches](#section-minute-based-searches)

[Permissions & Ownership](#category-permissions-ownership)

-   [Permission Tests](#section-permission-tests)
-   [User/Group Ownership](#section-user-group-ownership)
-   [Executable/Readable/Writable Tests](#section-executable-readable-writable)

[Advanced Operations](#category-advanced-operations)

-   [Logical Operators](#section-logical-operators)
-   [Directory Pruning](#section-directory-pruning)
-   [Regular Expressions](#section-regular-expressions)
-   [Execution with Files](#section-execution-with-files)

[Output & Actions](#category-output-actions)

-   [Print Options](#section-print-options)
-   [Deletion Actions](#section-deletion-actions)
-   [Advanced Exec Commands](#section-exec-commands)

[Practical Examples](#category-practical-examples)

-   [Real-World Use Cases](#section-real-world-use-cases)
-   [Performance Optimization](#section-performance-tips)

No commands found

Try adjusting your search term

## Getting Started

Introduction to find command and basic concepts

### What is Find

The find command and its purpose for filesystem searching

#### Accessibility

Clear introduction to find command concepts

#### Best Practices

-   Use -maxdepth to limit search depth and improve performance
-   Suppress permission errors with 2>/dev/null
-   Protect patterns with quotes to prevent shell expansion
-   Combine criteria for efficient searches

#### Common Errors

-   **Permission denied:** Use 2>/dev/null to suppress permission errors or run with elevated privileges

#### Keywords

findsearchfilesystemfilesdirectory

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Find command overview and basic syntax

Find walks the filesystem tree starting from the specified path, showing found items that match criteria.

Code

Terminal window

```
# Find command: search filesystem for files matching criteria# Syntax: find [path] [options] [expression]
# Key advantages:# - Search by name, size, type, time, permissions# - Walk directory trees recursively# - Execute commands on found files# - Filter by file properties# - Combine multiple criteria with logical operators
# Basic structure:# find /search/path -name "pattern"# find . -type f -size +1M# find /var/log -mtime +30
```

Execution

Terminal window

```
find /home -maxdepth 2 -type d 2>/dev/null | head -5
```

Output

Terminal window

```
/home/home/user/home/user/Documents/home/user/Downloads/home/user/Desktop
```

-   Find searches recursively by default
-   \-maxdepth limits directory traversal depth
-   Returns full paths to found files
-   Redirect stderr (2>/dev/null) to hide permission errors

#### Find vs other search tools

Find handles complex searches that combine multiple criteria like file type, name pattern, and location.

Code

Terminal window

```
# Compare find with similar tools:# find: Search filesystem by name, size, type, time, permissions# locate: Fast search using pre-built database# grep: Search within file contents (text)# ls: List directory contents (no recursive search)
# Use find when you need:# - Recursive filesystem search# - Filter by file properties (size, type, time, permissions)# - Execute commands on found files# - Complex search criteria# - Real-time search (database not needed)
```

Execution

Terminal window

```
find /tmp -maxdepth 1 -type f -name "*.tmp" 2>/dev/null | wc -l
```

Output

Terminal window

```
3
```

-   Find is more flexible than locate for custom criteria
-   Slower than locate but more current
-   Can execute actions on matched files
-   Better for scripts and automation

### Installation and Setup

Installing and verifying find functionality on different systems

#### Accessibility

Installation and verification instructions

#### Best Practices

-   Verify find is available before writing scripts
-   Use absolute paths to find command in scripts
-   Test on target system if compatibility is needed

#### Common Errors

-   **find: command not found:** Install findutils package using system package manager

#### Keywords

installsetupversionverifytest

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Verify find installation

Find is typically pre-installed on Linux systems. Verify availability and version.

Code

Terminal window

```
# Check if find is installedwhich find
# Display find versionfind --version
# Show find helpfind --help | head -20
```

Execution

Terminal window

```
which find && find --version | head -1
```

Output

Terminal window

```
/usr/bin/findfind version 4.8.0
```

-   Find is standard on all Unix-like systems
-   Different versions available: GNU find, BSD find
-   GNU find has more options
-   BSD find is on macOS by default

#### Install find on different systems

Find is available on all standard Linux systems and macOS, usually pre-installed.

Code

Terminal window

```
# Ubuntu/Debiansudo apt-get updatesudo apt-get install -y findutils
# CentOS/RHELsudo yum install -y findutils
# Alpine Linuxapk add findutils
# Arch Linuxsudo pacman -S findutils
# macOS (usually pre-installed)brew install findutils  # Installs GNU find as gfind
```

Execution

Terminal window

```
find /usr/bin -name "find" -o -name "gfind"
```

Output

Terminal window

```
/usr/bin/find
```

-   Findutils package provides GNU find
-   macOS comes with BSD find by default
-   Install GNU find (gfind) on macOS for compatibility
-   Always available on modern Linux distributions

## Basic Search

Simple file searching by name and basic patterns

### Simple Name Search

Basic file searching by name patterns

#### Accessibility

Clear examples of name-based searching

#### Best Practices

-   Use quotes around patterns to prevent shell expansion
-   Use -maxdepth to limit search depth for performance
-   Use -type f to search only files (not directories)

#### Common Errors

-   **No results found:** Verify pattern is correct and path is accessible

#### Keywords

searchname\-namepatternfile

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Search for files by exact name

Find searches recursively from the specified path for files matching the name pattern.

Code

Terminal window

```
# Find files by exact namefind . -name "filename.txt"
# Search in specific directoryfind /home -name "*.log"
# Search entire filesystemfind / -name "config.ini"
# Multiple directoriesfind /etc /var -name "*.conf"
```

Execution

Terminal window

```
find /tmp -name "*.tmp" 2>/dev/null | head -3
```

Output

Terminal window

```
/tmp/file1.tmp/tmp/cache/file2.tmp/tmp/sessions/file3.tmp
```

-   Pattern matching uses shell-style wildcards
-   \* matches any characters in a filename
-   matches single character:
-   \[ \] matches character ranges
-   Search is recursive through all subdirectories

#### Name search with wildcards

Wildcard patterns provide flexible name matching for common file extensions and naming conventions.

Code

Terminal window

```
# Find all Python filesfind . -name "*.py"
# Find by prefixfind . -name "test_*"
# Find by suffixfind . -name "*.backup"
# Complex patternsfind . -name "*[0-9].txt"  # filenames with digits
```

Execution

Terminal window

```
find /home -maxdepth 2 -name "*.md" 2>/dev/null | head -5
```

Output

Terminal window

```
/home/user/README.md/home/user/Documents/guide.md/home/user/Downloads/tutorial.md
```

-   \* matches zero or more characters
-   matches exactly one character:
-   Patterns are case-sensitive
-   Use quotes to prevent shell expansion

### Case-Insensitive Search

Search for files ignoring case sensitivity

#### Accessibility

Case-insensitive search examples

#### Best Practices

-   Use -iname when case is uncertain
-   Combine with -type to filter results
-   Use -maxdepth to improve performance

#### Common Errors

-   **iname: No such option:** Use -iname with newer find versions; older BSD find may need different approach

#### Keywords

caseinsensitive\-inameignorecase

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Case-insensitive file name search

The -iname flag performs case-insensitive filename matching, useful when unsure of case.

Code

Terminal window

```
# -iname flag for case-insensitive matchingfind . -iname "README.txt"
# Matches: readme.txt, README.TXT, ReadMe.txt, etc.find . -iname "*.LOG"
# Case-insensitive wildcard patternsfind /var -iname "*.pdf"
```

Execution

Terminal window

```
find /home -maxdepth 2 -iname "*.LOG" 2>/dev/null
```

Output

Terminal window

```
/home/user/app.log/home/user/system/ERROR.LOG
```

-   \-iname is case-insensitive version of -name
-   Matches regardless of upper/lowercase
-   Combines with wildcards for flexible searching
-   Slower than -name (case-sensitive)

#### Mixed case pattern matching

Case-insensitive searching helps find files when exact case is unknown.

Code

Terminal window

```
# Search for backup files regardless of casefind . -iname "*.backup"  # .backup, .BACKUP, .Backup
# Configuration files with various casesfind /etc -iname "*.conf"
# Executable scripts (any case)find . -iname "*install*"
```

Execution

Terminal window

```
find /tmp -maxdepth 1 -iname "test*" 2>/dev/null | head -5
```

Output

Terminal window

```
/tmp/test_file.txt/tmp/TEST_data/tmp/Test_logs.txt
```

-   Useful for cross-platform searches
-   Handles case variations in naming
-   Works with all wildcard patterns

### Path Matching

Search by full path or path patterns

#### Accessibility

Path-based search examples

#### Best Practices

-   Use -prune to exclude heavy directories like node\_modules
-   Test path patterns on sample directory first
-   Use quotes to prevent shell expansion of path characters

#### Common Errors

-   **Unexpected operator or missing operand:** Properly quote path patterns and use parentheses for grouping

#### Keywords

path\-pathdirectorylocationroute

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Search by full path pattern

\-path matches the entire path from start, useful for excluding directories or matching nested structures.

Code

Terminal window

```
# -path for full path matchingfind . -path "*node_modules*"
# Match specific directory structurefind . -path "*/src/components/*.js"
# Exclude patterns with -notfind . -path "*node_modules" -prune -o -name "*.js" -print
# Case-insensitive path matchingfind . -ipath "*/downloads/*"
```

Execution

Terminal window

```
find /home -maxdepth 3 -path "*Document*" 2>/dev/null
```

Output

Terminal window

```
/home/user/Documents/home/user/Documents/files
```

-   \-path matches from start of path being tested
-   \* matches path separators (unlike -name)
-   \-ipath is case-insensitive version
-   Use -prune to skip directories efficiently

#### Path matching with directory pruning

Combining -prune with -o (or) and -print skips whole directories without descending into them while still finding matching files.

Code

Terminal window

```
# Find JavaScript files, skip node_modulesfind . -name "node_modules" -prune -o -name "*.js" -print
# Exclude multiple directoriesfind . \( -path "*/node_modules" -o -path "*/.git" \) -prune -o -name "*.ts" -print
# Find test files, exclude temp directoriesfind . -path "*/temp" -prune -o -name "*test*" -print
```

Execution

Terminal window

```
find /home -maxdepth 3 -name ".git" -prune -o -type f -name "*.py" -print 2>/dev/null | head -3
```

Output

Terminal window

```
/home/user/script.py/home/user/projects/tool.py/home/user/projects/utils.py
```

-   \-prune skips entire directory without descending
-   More efficient than grep/filter after find
-   Use with logical operators for complex patterns

### Type Matching

Search by file type (regular files, directories, symlinks, etc.)

#### Accessibility

File type filtering examples

#### Best Practices

-   Use -type f with name patterns for accuracy
-   Combine -type with other filters for efficiency
-   Use -type d to find only directories

#### Common Errors

-   **Wrong file type matched:** Verify -type flag is included in command

#### Keywords

type\-typefiledirectorysymlink

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Search by file type

\-type d filters to show only directories, excluding regular files and other types.

Code

Terminal window

```
# -type flag specifies file type# f = regular file# d = directory# l = symbolic link# c = character device# b = block device# p = named pipe# s = socket
find . -type f       # regular files onlyfind . -type d       # directories onlyfind . -type l       # symbolic linksfind /dev -type c    # character devices
```

Execution

Terminal window

```
find /home -maxdepth 2 -type d 2>/dev/null | head -5
```

Output

Terminal window

```
/home/home/user/home/user/Documents/home/user/Downloads/home/user/Desktop
```

-   f for regular files is most common type
-   d for directories, l for symlinks
-   Device types (c, b) typically in /dev
-   Type matching improves search efficiency

#### Combining type with name search

Combining -type f with -name "\*.md" finds only regular markdown files, excluding directories.

Code

Terminal window

```
# Find Python files (regular files only)find . -type f -name "*.py"
# Find directories matching patternfind . -type d -name "*test*"
# Find symlinks to filesfind . -type l -name "*.txt"
# Find broken symlinks (point to nothing)find . -type l ! -exec test -e {} \;
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f -name "*.md" 2>/dev/null | head -3
```

Output

Terminal window

```
/home/user/README.md/home/user/Documents/guide.md/home/user/Downloads/tutorial.md
```

-   Always use -type f with name patterns for efficiency
-   Reduces false positives from directories
-   Works with other criteria like size and time

## File Size & Type

Filter files by size and specific type tests

### Size Filtering

Search files by size with various units and comparisons

#### Accessibility

Size-based file filtering examples

#### Best Practices

-   Use size filtering to identify disk space hogs
-   Combine multiple size criteria for ranges
-   Use with deletion carefully (-delete flag)

#### Common Errors

-   **Size units not recognized:** Use valid units: c, k, M, G only

#### Keywords

size\-sizebyteskilobytesfilter

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Find files by size

\-size finds files larger than 10MB, useful for identifying large files consuming disk space.

Code

Terminal window

```
# -size flag for file size filtering# c = bytes# k = kilobytes (1024 bytes)# M = megabytes (1024 KB)# G = gigabytes (1024 MB)
find . -size +1M        # larger than 1MBfind . -size -1M        # smaller than 1MBfind . -size 100c       # exactly 100 bytesfind . -size 5k         # exactly 5 kilobytes
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f -size +10M 2>/dev/null
```

Output

Terminal window

```
/home/user/Downloads/large_video.mp4/home/user/backup/archive.tar.gz
```

-   \+ means larger than, - means smaller than
-   No prefix means exactly that size
-   Units: c (bytes), k (1024 bytes), M (1024 KB), G (1024 MB)
-   Size is rounded, so +1M includes files > 1,048,576 bytes

#### Find disk space hogs

Combining size criteria finds files in specific size ranges for storage analysis.

Code

Terminal window

```
# Find large files for cleanupfind . -type f -size +100M
# Find files exactly 1MBfind . -type f -size 1M
# Range of sizesfind . -type f -size +1M -size -100M
# Empty files (special case)find . -type f -size 0
```

Execution

Terminal window

```
find /tmp -type f -size +1M 2>/dev/null
```

Output

Terminal window

```
/tmp/cache/large.dat
```

-   Size filtering helps manage disk usage
-   Use + and - to define ranges
-   Combine with -type f for accuracy

### File Type Tests

Test file type with specific attributes

#### Accessibility

File type testing examples

#### Best Practices

-   Use -type for efficiency before other tests
-   Combine type tests with other criteria
-   Test symlinks with -type l -xtype l

#### Common Errors

-   **File not found for symlink:** Use -type l to find symlinks, not -xtype for broken links

#### Keywords

typetest\-typedevicesocket

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Search by specific file types

Find searches for character devices in /dev, which are special file types representing hardware.

Code

Terminal window

```
# Find symbolic linksfind . -type l
# Find character devicesfind /dev -type c
# Find block devicesfind /dev -type b
# Find named pipes (FIFOs)find /tmp -type p
# Find socketsfind /run -type s
```

Execution

Terminal window

```
find /dev -maxdepth 1 -type c 2>/dev/null | head -3
```

Output

Terminal window

```
/dev/null/dev/zero/dev/random
```

-   l = symlinks, c = character devices, b = block devices
-   Useful for system administration tasks
-   Device files in /dev controlled by kernel

#### Advanced type combinations

Finding symbolic links helps identify shortcuts and dependencies in the filesystem.

Code

Terminal window

```
# Find broken symlinksfind . -type l -xtype l
# Find symlinks to directoriesfind . -type l
# Find all non-regular filesfind . ! -type f
# Find files and directories (not devices)find . \( -type f -o -type d \)
```

Execution

Terminal window

```
find /home -maxdepth 3 -type l 2>/dev/null | head -3
```

Output

Terminal window

```
/home/user/.oh-my-zsh -> /usr/share/oh-my-zsh/home/user/.config/app/plugins -> ../../../opt/plugins
```

-   \-xtype tests the type of file link points to
-   operator negates conditions
-   Parentheses group conditions with -o (or)

### Empty Files

Search for empty files and directories

#### Accessibility

Empty file search examples

#### Best Practices

-   Use -ls before -delete to verify results
-   Test find command without -delete first
-   Use -exec rm -i for safer deletion

#### Common Errors

-   **Deleted wrong files:** Always preview with find first, verify criteria before using -delete

#### Keywords

emptysize\-sizezeroblank

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Find empty files and directories

Find locates empty files with -size 0 or using -empty test flag.

Code

Terminal window

```
# Find empty regular filesfind . -type f -size 0
# Find empty directoriesfind . -type d -empty
# Find and delete empty filesfind . -type f -size 0 -delete
# Find empty files with timestamp infofind . -type f -size 0 -ls
```

Execution

Terminal window

```
find /tmp -maxdepth 2 -type f -size 0 2>/dev/null | head -3
```

Output

Terminal window

```
/tmp/placeholder.txt/tmp/cache/empty.log
```

-   \-size 0 finds files with zero bytes
-   \-empty tests both empty files and directories
-   Useful for cleanup operations
-   Be careful with -delete flag

#### Cleanup empty files

Combining -empty with -delete removes empty files, useful for storage cleanup.

Code

Terminal window

```
# Count empty filesfind . -type f -size 0 | wc -l
# Remove empty files and directoriesfind . -type f -empty -deletefind . -type d -empty -delete
# Safe delete with confirmationfind . -type f -size 0 -exec rm -i {} \;
```

Execution

Terminal window

```
find /tmp -maxdepth 1 -type f -empty 2>/dev/null | wc -l
```

Output

Terminal window

```
2
```

-   \-delete removes found items permanently
-   \-exec with -i provides confirmation before delete
-   Test before deleting on important filesystems

## Time-Based Search

Search files by modification, access, and change times

### Modification Time

Search files by modification time

#### Accessibility

Modification time search examples

#### Best Practices

-   Use -mtime for day-level time filtering
-   Combine with -type f for regular files only
-   Test criteria before using -delete

#### Common Errors

-   **Wrong time period matched:** Remember +n (older), -n (newer), 0 (today)

#### Keywords

mtimemodifiedtimedays\-mtime

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Find files by modification time

Find locates files modified more than 30 days ago, useful for archiving old logs.

Code

Terminal window

```
# -mtime flag: modification time in days# n = exactly n days old# +n = more than n days old# -n = less than n days old
find . -mtime 0       # modified todayfind . -mtime 1       # modified exactly 1 day agofind . -mtime +30     # modified more than 30 days agofind . -mtime -7      # modified in last 7 days
```

Execution

Terminal window

```
find /var/log -maxdepth 1 -type f -mtime +30 2>/dev/null
```

Output

Terminal window

```
/var/log/syslog.1/var/log/secure.log
```

-   mtime is modification time in complete days
-   +30 means more than 30 days (older)
-   \-7 means less than 7 days (newer)
-   0 means today (last 24 hours)

#### Archive old files

Find can identify recently modified files for backup or analysis purposes.

Code

Terminal window

```
# Find and archive logs older than 90 daysfind /var/log -type f -mtime +90 | tar czf archive.tar.gz --files-from=-
# Find old backup files and deletefind /backups -type f -name "*.bak" -mtime +365 -delete
# Find recently modified filesfind . -type f -mtime -1  # last 24 hours
```

Execution

Terminal window

```
find /tmp -maxdepth 2 -type f -mtime 0 2>/dev/null | head -3
```

Output

Terminal window

```
/tmp/session-20250228.dat/tmp/cache/update.log
```

-   \-mtime 0 means modified since midnight
-   Use with -mmin for minute-level precision
-   Useful for automated cleanup scripts

### Access Time

Search files by access time (when file was read)

#### Accessibility

Access time search examples

#### Best Practices

-   Check if filesystem uses atime (may be disabled for performance)
-   Combine atime with mtime for better analysis
-   Use -amin for minute-level access time searches

#### Common Errors

-   **atime not updating:** Some filesystems have noatime option; check mount options with mount command

#### Keywords

atimeaccess\-atimereadtime

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Find files by access time

Find files not accessed for more than 6 months, candidates for archiving.

Code

Terminal window

```
# -atime flag: access time (last read)find . -atime 0        # accessed todayfind . -atime +30      # accessed more than 30 days agofind . -atime -7       # accessed in last 7 days
# Find files never accessed since modificationfind . -amin -10       # accessed in last 10 minutes
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f -atime +180 2>/dev/null | head -3
```

Output

Terminal window

```
/home/user/.cache/old_cache.db/home/user/Documents/archive.zip
```

-   atime = access time (when file was read)
-   Measured in days with -atime
-   Use -amin for minute precision
-   Some filesystems disable atime for performance

#### Find unused files for cleanup

Finding rarely accessed files helps identify candidates for removal to free disk space.

Code

Terminal window

```
# Find files not accessed in a yearfind . -type f -atime +365
# Find large files not accessed recentlyfind . -type f -size +1M -atime +90
# List files with access time infofind . -type f -atime +30 -ls
```

Execution

Terminal window

```
find /tmp -maxdepth 1 -type f -atime +7 2>/dev/null | head -2
```

Output

Terminal window

```
/tmp/download.tmp
```

-   atime tracking may be disabled on some systems
-   Combine with size for storage analysis
-   Use with -ls to see file details

### Change Time

Search files by change time (metadata changes)

#### Accessibility

Change time search examples

#### Best Practices

-   Use ctime to detect permission and ownership changes
-   Combine ctime and mtime for a fuller analysis
-   Monitor system files for unauthorized changes

#### Common Errors

-   **Confusing ctime with mtime:** ctime=metadata changes, mtime=content changes

#### Keywords

ctimechange\-ctimemetadatainode

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Find files by change time

Find system configuration files changed in the last 24 hours (permissions or ownership changes).

Code

Terminal window

```
# -ctime flag: change time (inode changes)# Changed when: content modified, permissions changed, owner changedfind . -ctime 0        # changed todayfind . -ctime +7       # changed more than 7 days agofind . -ctime -1       # changed in last 24 hours
# Find files with recent permission changesfind . -ctime -1 ! -mtime -1
```

Execution

Terminal window

```
find /etc -maxdepth 1 -type f -ctime -1 2>/dev/null | head -3
```

Output

Terminal window

```
/etc/shadow/etc/passwd
```

-   ctime = change time (metadata like permissions, ownership)
-   Different from mtime (content modification)
-   Updated when inode information changes
-   Useful for detecting permission changes

#### Monitor configuration changes

Find files with recent timestamp or permission modifications for monitoring system changes.

Code

Terminal window

```
# Find config files changed recentlyfind /etc -name "*.conf" -ctime -1
# Find permission changes (ctime but not mtime change)find . -ctime -1 ! -mtime -1
# System changes detectionfind /etc -type f -ctime -7
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f -ctime -1 2>/dev/null | head -3
```

Output

Terminal window

```
/home/user/.bash_history/home/user/.cache/recent.db
```

-   Useful for security monitoring
-   Detects permission/ownership changes
-   Different from mtime for pure content changes

### Minute-Based Searches

Search files by minute-level time precision

#### Accessibility

Minute-level time search examples

#### Best Practices

-   Use -mmin for recent file monitoring
-   Combine with -ls for detailed output
-   Use in watch loops for continuous monitoring

#### Common Errors

-   **Too many results with -mmin:** Use smaller time windows and filters

#### Keywords

minute\-mmin\-amin\-cmintime

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Find files by minute-level time

Find files modified in the last 10 minutes for monitoring recent activity.

Code

Terminal window

```
# -mmin, -amin, -cmin for minute precision# Same operators as day versions
find . -mmin -5        # modified in last 5 minutesfind . -mmin 0         # modified in current minutefind . -amin +60       # not accessed in 60+ minutesfind . -cmin -10       # changed in last 10 minutes
```

Execution

Terminal window

```
find /tmp -maxdepth 1 -type f -mmin -10 2>/dev/null | head -3
```

Output

Terminal window

```
/tmp/session.log/tmp/cache/update.dat
```

-   \-mmin uses minutes instead of days
-   Same operators: +n (older), -n (newer)
-   \-amin for access time in minutes
-   \-cmin for change time in minutes

#### Real-time file monitoring

Minute-level searches enable real-time monitoring of file activity.

Code

Terminal window

```
# Find files modified in last minutefind /var/log -type f -mmin -1
# Find recently created filesfind . -type f -cmin -2
# Monitor temp directorywatch -n 60 'find /tmp -type f -mmin -5'
# Activity monitoring scriptwhile true; do find . -type f -mmin -1; sleep 60; done
```

Execution

Terminal window

```
find /var -maxdepth 1 -type f -mmin -30 2>/dev/null | head -3
```

Output

Terminal window

```
/var/adm/sulog/var/syslog/current
```

-   Useful for logs and activity monitoring
-   Can be used in watch loops
-   Helpful for debugging and troubleshooting

## Permissions & Ownership

Search files by permissions and ownership

### Permission Tests

Search files by permission settings

#### Accessibility

Permission-based search examples

#### Best Practices

-   Regularly audit SUID/SGID files
-   Prevent world-writable files in sensitive areas
-   Check what each permission bit grants before changing it

#### Common Errors

-   **Permission matching not working:** Use correct format: -perm exactly, -perm -at least, -perm /any bit

#### Keywords

permissions\-permmodechmodaccess

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Find files by permission

Find files with exactly 644 permissions (rw-r--r--), common for regular files.

Code

Terminal window

```
# -perm flag for permission matchingfind . -perm 644       # exactly 644 (rw-r--r--)find . -perm -644      # has at least these permissionsfind . -perm /644      # matches any of these bitsfind . -perm u+x       # user executablefind . -perm -u=rwx    # has all permissions for user
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f -perm 644 2>/dev/null | head -3
```

Output

Terminal window

```
/home/user/.bashrc/home/user/file.txt/home/user/Documents/readme.md
```

-   \-perm mode matches exactly that permission mode
-   \-perm -mode matches files with at least those permissions
-   \-perm /mode matches any of the specified bits
-   Modes can be octal (644) or symbolic (a+r)

#### Find dangerous permissions

Find SUID files which run with owner privileges, security-critical to monitor.

Code

Terminal window

```
# Find world-writable filesfind . -perm -o=w
# Find SUID filesfind / -perm -u+s
# Find SGID filesfind / -perm -g+s
# Find sticky bit filesfind / -perm -u+t
# Find world-readable sensitive filesfind /etc -type f -perm -o=r
```

Execution

Terminal window

```
find /usr -maxdepth 2 -type f -perm -u+s 2>/dev/null | head -3
```

Output

Terminal window

```
/usr/bin/sudo/usr/bin/passwd/usr/bin/chfn
```

-   \-o=w finds world-writable files (security risk)
-   \-u+s finds SUID bits (runs as owner)
-   \-g+s finds SGID bits (runs as group)
-   u+t finds sticky bit (often on /tmp)

### User/Group Ownership

Search files by user or group ownership

#### Accessibility

Ownership-based search examples

#### Best Practices

-   Use -user to find owned files for backup
-   Use -group for group-based permission audits
-   Combine with -perm for a thorough security review

#### Common Errors

-   **User/group name not found:** Verify username/group exists in /etc/passwd or /etc/group

#### Keywords

usergroup\-user\-groupowner

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Find files by user ownership

Find files owned by root in user directories, potentially security issues.

Code

Terminal window

```
# -user flag for user ownershipfind . -user root       # owned by rootfind . -user nobody     # owned by nobody userfind /home -user $USER  # files owned by current userfind . ! -user root     # NOT owned by root
# Find files by numeric UIDfind . -uid 1000        # files with UID 1000
```

Execution

Terminal window

```
find /home -maxdepth 2 -user root 2>/dev/null | head -3
```

Output

Terminal window

```
/home/shared/admin-config/home/shared/system-backup
```

-   \-user looks up username from /etc/passwd
-   \-uid uses numeric user ID directly
-   \-user negates the condition
-   $USER expands to current username

#### Find files by group ownership

Find directories owned by the 'users' group.

Code

Terminal window

```
# -group flag for group ownershipfind . -group admin     # group-owned by adminfind . -group staff     # group stafffind /tmp -group root   # temp files owned by rootfind . ! -group wheel   # NOT group wheel
# Find files by numeric GIDfind . -gid 1001        # files with GID 1001
```

Execution

Terminal window

```
find /home -maxdepth 1 -type d -group users 2>/dev/null
```

Output

Terminal window

```
/home/user1/home/user2
```

-   \-group looks up group name from /etc/group
-   \-gid uses numeric group ID directly
-   \-group negates the condition

### Executable/Readable/Writable Tests

Search files by specific permission tests

#### Accessibility

Specific file permission testing examples

#### Best Practices

-   Use -executable to find scripts and binaries
-   Use -readable/-writable for access checks
-   Combine with -user/-group for ownership verification

#### Common Errors

-   **Permissions show different from -perm:** -executable/-readable/-writable test actual user access, -perm tests file mode

#### Keywords

executablereadablewritable\-executable\-readable\-writable

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Find executable files

Find executable files matching a pattern, such as shell commands like ls.

Code

Terminal window

```
# -executable tests if file is executable by current userfind . -type f -executable
# Executable scriptsfind . -type f -executable -name "*.sh"
# Non-executable regular filesfind . -type f ! -executable
# Find executable in PATHfind $PATH -type f -executable -name "find"
```

Execution

Terminal window

```
find /usr/bin -maxdepth 1 -type f -executable -name "ls*" 2>/dev/null
```

Output

Terminal window

```
/usr/bin/ls
```

-   \-executable tests if current user can execute
-   Works with -name for specific executable search
-   \-executable finds non-executable files
-   Useful for security audits

#### Find readable and writable files

Find read-only files which are readable but not writable by current user.

Code

Terminal window

```
# -readable tests if file is readable by current userfind . -type f -readable
# -writable tests if file is writable by current userfind . -type f -writable
# Files readable but not writablefind . -type f -readable ! -writable
# Writable-only files (unusual)find . -type f ! -readable -writable
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f -readable ! -writable 2>/dev/null | head -3
```

Output

Terminal window

```
/home/user/important.txt/home/user/Documents/archive
```

-   \-readable tests read permission for current user
-   \-writable tests write permission
-   Respects user's actual permissions
-   Useful for access verification

## Advanced Operations

Complex operations combining multiple criteria

### Logical Operators

Combine multiple search criteria using logical operators

#### Accessibility

Logical operator combination examples

#### Best Practices

-   Use parentheses to clarify expression intent
-   Test complex expressions on sample data first
-   Use path exclusions early for performance

#### Common Errors

-   **Unexpected operator:** Escape parentheses with backslash: \\\\( \\\\)

#### Keywords

logicaloperators\-and\-or\-not

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Combine conditions with AND and OR

Find files with either .py or .js extension using OR operator with parentheses.

Code

Terminal window

```
# -and (implicit between conditions)find . -type f -name "*.py"  # type AND name
# -o for OR operatorfind . \( -name "*.py" -o -name "*.js" \)
# ! for NOT operatorfind . ! -name "*.tmp"
# Complex combinationsfind . -type f \( -name "*.log" -o -name "*.txt" \) -size +1M
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f \( -name "*.py" -o -name "*.js" \) 2>/dev/null | head -3
```

Output

Terminal window

```
/home/user/script.py/home/user/app.js/home/user/projects/utils.py
```

-   Multiple conditions are AND by default (implicit)
-   \-o provides OR logic
-   ! provides NOT logic
-   Parentheses group conditions
-   Escape parentheses in shell: \\( \\)

#### Complex logical expressions

Find large document files combining OR logic with size filtering.

Code

Terminal window

```
# Find large files modified today OR accessed recentlyfind . -size +10M \( -mtime 0 -o -atime -1 \)
# Find Python files not in test directoryfind . -name "*.py" ! -path "*/test*"
# Find recently modified OR changed filesfind . \( -mtime -1 -o -ctime -1 \) -type f
# Complex: large old files not backed upfind . -size +100M -mtime +90 ! -name "*.backup"
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f \( -name "*.pdf" -o -name "*.doc" \) -size +1M 2>/dev/null | head -3
```

Output

Terminal window

```
/home/user/Documents/thesis.pdf/home/user/Downloads/manual.pdf
```

-   Group with parentheses for complex expressions
-   AND binds tighter than OR in traditional logic
-   Parentheses set the evaluation order explicitly

### Directory Pruning

Skip directories to improve search performance

#### Accessibility

Directory pruning examples

#### Best Practices

-   Always prune node\_modules in JavaScript projects
-   Prune .git, .venv, build directories
-   Test with -prune to verify correct directories are skipped

#### Common Errors

-   **Still searching in excluded directories:** Put -prune in the correct logical position, before the action

#### Keywords

pruneskip\-prunedirectoryexclude

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Prune directories to skip recursion

Prune .cache directory to skip hidden cache, finding only markdown files.

Code

Terminal window

```
# -prune skips directory without descendingfind . -name "node_modules" -prune -o -name "*.js" -print
# Skip multiple directoriesfind . \( -path "*/node_modules" -o -path "*/.git" \) -prune -o -type f -print
# Skip .git and .venvfind . -name ".git" -prune -o -name ".venv" -prune -o -type f -print
# Common excluded directoriesfind . -path "*/.git" -prune -o -path "*/node_modules" -prune -o -type f -print
```

Execution

Terminal window

```
find /home -maxdepth 2 -name ".cache" -prune -o -type f -name "*.md" -print 2>/dev/null | head -3
```

Output

Terminal window

```
/home/user/README.md/home/user/Projects/guide.md
```

-   \-prune stops descending into matched directories
-   Much faster than searching and filtering
-   Used in "path -prune -o action -print" pattern
-   \-o (or) follows -prune for alternative action

#### Efficient recursive search with prune

Pruning several directories at once keeps the search from descending into unneeded paths.

Code

Terminal window

```
# Find source files, skip build and cachefind . -type d \( -name "build" -o -name "dist" -o -name ".cache" \) -prune -o -type f -name "*.src" -print
# Search for config files, skip system directoriesfind /home -type d -name ".config" -prune -o -name "config.json" -print
# Find all files, avoid large directoriesfind . \( -name "node_modules" -o -name ".git" -o -name "venv" \) -prune -o -type f -print
```

Execution

Terminal window

```
find /tmp -maxdepth 3 \( -name ".git" -o -name ".cache" \) -prune -o -type f -print 2>/dev/null | head -3
```

Output

Terminal window

```
/tmp/session.log/tmp/data/config.json
```

-   Parentheses group multiple -name conditions
-   \-o separates multiple directories to prune
-   Results in much faster searches
-   Especially useful for projects with large dependencies

### Regular Expressions

Use regex patterns for matching in find

#### Accessibility

Regular expression pattern examples

#### Best Practices

-   Use -name for simple patterns (faster)
-   Use -regex for complex patterns
-   Anchor patterns with ^ and $ where needed

#### Common Errors

-   **Regex not matching expected files:** Remember -regex matches full path from current directory

#### Keywords

regexexpression\-regex\-iregexpattern

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Find with regular expressions

Find PDF files using regex pattern matching full path.

Code

Terminal window

```
# -regex for full path regex matchingfind . -regex ".*\.py$"          # Python filesfind . -regex ".*test.*\.js$"    # test JavaScript filesfind . -regex ".*/src/.*\.ts$"   # TypeScript in src/
# -iregex for case-insensitivefind . -iregex ".*\.(log|txt)$"  # .log or .txt files (case-insensitive)
# Regex with character classesfind . -regex ".*[0-9]\{4\}\.txt$"  # files with 4 digits before .txt
```

Execution

Terminal window

```
find /home -maxdepth 3 -regex ".*\.pdf$" 2>/dev/null | head -3
```

Output

Terminal window

```
/home/user/Documents/report.pdf/home/user/manual.pdf
```

-   \-regex matches full path (not just filename)
-   Pattern is extended regex by default
-   .\* matches any characters to root
-   $ anchors match path end
-   Slower than -name but more flexible

#### Complex regex patterns

Find log and temp files using regex pattern with alternation.

Code

Terminal window

```
# Find versioned filesfind . -regex ".*v[0-9]+\.[0-9]+\.txt$"
# Find config files in specific structurefind . -regex ".*/config/[^/]*\.json$"
# Find date-named filesfind . -regex ".*[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}.*"
# Find non-dotfilesfind . -regex ".*/[^.][^/]*$"
```

Execution

Terminal window

```
find /var -maxdepth 2 -regex ".*\.(log|tmp)$" 2>/dev/null | head -3
```

Output

Terminal window

```
/var/log/syslog.log/var/tmp/session.tmp
```

-   Regex matches patterns that -name cannot express
-   Performance cost vs simple -name
-   Extended regex is default (no need to escape special chars in \[\])

### Execution with Files

Execute commands on found files safely

#### Accessibility

Command execution examples

#### Best Practices

-   Always test -exec commands without actual execution first
-   Use + instead of \\\\\\; for better performance
-   Use -ok for interactive confirmation on important operations

#### Common Errors

-   **Command not executing or syntax error:** Verify {} and \\\\; are present; test quoting

#### Keywords

execution\-exec\-execdirxargscommand

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Execute commands with -exec

Execute ls command on each found .txt file showing detailed information.

Code

Terminal window

```
# -exec runs command on each found file# {} placeholder replaced with filename# ; terminates command (escape with \;)
find . -name "*.log" -exec rm {} \;find . -type f -exec chmod 644 {} \;find . -name "*.py" -exec python3 {} \;
# -exec with outputfind . -type f -exec wc -l {} \;
```

Execution

Terminal window

```
find /tmp -maxdepth 1 -type f -name "*.txt" -exec ls -lh {} \; 2>/dev/null
```

Output

Terminal window

```
-rw-r--r-- 1 user user 12K /tmp/file1.txt-rw-r--r-- 1 user user 5.2K /tmp/file2.txt
```

-   {} is placeholder for found filename
-   \\\\; terminates the command
-   Spawns new process for each file
-   Can be slow with many files

#### Safe and efficient execution

Use + instead of ; to pass multiple files to command for efficiency.

Code

Terminal window

```
# -exec with + instead of ; (more efficient)find . -type f -exec grep -l "TODO" {} +
# -execdir runs in file's directoryfind . -type f -name "*.bak" -execdir rm {} \;
# Interactive prompt with -okfind . -type f -name "*.tmp" -ok rm {} \;
# Use xargs for better performancefind . -type f -print0 | xargs -0 rm
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f -name "*.md" -exec wc -l {} + 2>/dev/null | tail -1
```

Output

Terminal window

```
42 total
```

-   \+ batches files into single command call (more efficient)
-   \-execdir changes to file directory before executing
-   \-ok prompts before each execution
-   \-print0 with xargs handles spaces in filenames

#### Common exec patterns

Execute base64 encoding on found files.

Code

Terminal window

```
# Remove old filesfind . -type f -mtime +90 -exec rm -f {} \;
# Change permissionsfind . -type f -exec chmod 644 {} +find . -type d -exec chmod 755 {} +
# Show file informationfind . -type f -name "*.log" -exec ls -lh {} \;
# Compress old logsfind /var/log -type f -mtime +30 -exec gzip {} \;
```

Execution

Terminal window

```
find /tmp -maxdepth 1 -type f -exec base64 {} \\; 2>/dev/null | head -2
```

Output

Terminal window

```
ZmlsZSBjb250ZW50IGluIGJhc2U2NAo=
```

-   Common use: rm, chmod, gzip, grep
-   Always test before destructive operations
-   Use + for better performance when possible

## Output & Actions

Control output format and perform actions on files

### Print Options

Format output from find command

#### Accessibility

Output formatting examples

#### Best Practices

-   Use -printf for structured output
-   Use -print0 with xargs for filename safety
-   Use -ls for quick detailed listing

#### Common Errors

-   **Unknown format specifier:** Use valid printf formats: %p, %s, %m, %u, %g, %T

#### Keywords

printoutput\-print\-printfformat

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Format find output

Custom printf format showing filename and size in bytes.

Code

Terminal window

```
# Default -print (newline separated)find . -name "*.py"      # same as: find . -name "*.py" -print
# -print0 for null-terminated (handles spaces)find . -type f -print0 | xargs -0 ls -la
# -printf for custom formattingfind . -type f -printf "%p %s bytes\n"
# Format options:# %p = path# %s = size# %m = permissions (octal)# %u = username# %g = group# %T = modification time
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f -printf "%f %s\n" 2>/dev/null | head -3
```

Output

Terminal window

```
bashrc 2145vimrc 5329config.json 1024
```

-   \-printf builds custom output format
-   %f = filename only, %p = full path
-   %s = size, %m = permissions
-   %u = user, %g = group
-   \\\\n for newline, \\\\t for tab

#### Advanced output formatting

Show owner, size, and filename in custom format.

Code

Terminal window

```
# File info with permissionsfind . -type f -printf "%m %u:%g %s %p\n"
# Size in human-readable formatfind . -type f -exec ls -lh {} + | awk '{print $9, $5}'
# JSON-like outputfind . -type f -printf "{\\"file\\": \\"%p\\", \\"size\\": %s}\n"
# List with timestampsfind . -type f -printf "%TY-%Tm-%Td %p\n"
```

Execution

Terminal window

```
find /tmp -maxdepth 1 -type f -printf "%u %s %f\n" 2>/dev/null | head -3
```

Output

Terminal window

```
root 2048 config.tmpuser 1024 session.dat
```

-   %T formatter for time (complex)
-   %m for octal permissions
-   Useful for parsing and post-processing

### Deletion Actions

Delete files matching criteria

#### Accessibility

File deletion examples

#### Best Practices

-   ALWAYS preview with find first before -delete
-   Use -ls to verify correct files will be deleted
-   Test on safe directory first
-   Use -ok rm instead of -delete for confirmation

#### Common Errors

-   **Deleted wrong files accidentally:** Always preview with find first, use small examples

#### Keywords

deleteremoval\-deletedangerouscleanup

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Delete files matching criteria

Delete all .tmp files in /tmp directory.

Code

Terminal window

```
# -delete removes found files# BE CAREFUL - permanent deletion!
find . -type f -name "*.tmp" -delete
# Delete empty filesfind . -type f -size 0 -delete
# Delete old filesfind /tmp -type f -mtime +30 -delete
# Delete in specific directoryfind /tmp -maxdepth 1 -type f -delete
```

Execution

Terminal window

```
find /tmp -maxdepth 1 -type f -name "*.tmp" -delete 2>/dev/null; echo "Deleted"
```

Output

Terminal window

```
Deleted
```

-   \-delete removes found items permanently
-   No confirmation or recovery possible
-   Always test command first
-   Consider backing up before bulk delete

#### Safe deletion with confirmation

List files with -ls before deletion for safety verification.

Code

Terminal window

```
# Preview before deletingfind . -name "*.log" -mtime +30  # preview first
# Then delete with confirmationfind . -name "*.log" -mtime +30 -ok rm {} \;
# Safe delete with listfind . -type f -size 0 -ls     # list empty filesfind . -type f -size 0 -delete # delete them
# Backup before deletionfind . -type f -mtime +365 -exec cp {} {}.backup \;find . -type f -mtime +365 -delete
```

Execution

Terminal window

```
find /tmp -maxdepth 2 -type f -name "test_*.log" -ls 2>/dev/null | head -1
```

Output

Terminal window

```
2097152  4 -rw-r--r-- 1 user user   2048 Feb 28 10:30 /tmp/test_run.log
```

-   Always preview with -ls or -printf before -delete
-   Use -ok with rm for interactive confirmation
-   Keep backups for important deletions

### Advanced Exec Commands

Complex command execution patterns

#### Accessibility

Advanced command execution examples

#### Best Practices

-   Use + for batching when possible (more efficient)
-   Escape special characters in complex commands
-   Test complex exec patterns in safe directories

#### Common Errors

-   **Syntax errors in complex exec commands:** Quote properly and test simple version first

#### Keywords

execcommandprocessingbatchvariables

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Process files with exec commands

Count lines in markdown files combining with + for batching.

Code

Terminal window

```
# Run command on each filefind . -type f -name "*.jpg" -exec file {} \;
# Batch process multiple filesfind . -name "*.txt" -exec cat {} + > combined.txt
# Get file infofind . -type f -exec stat {} \;
# Process with pipesfind . -type f -exec grep -l "error" {} \;
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f -name "*.md" -exec wc -l {} + 2>/dev/null
```

Output

Terminal window

```
42 /home/user/README.md15 /home/user/GUIDE.md57 total
```

-   {} is replaced with found filename
-   \+ batches multiple files in single command call
-   \\\\; runs command for each file separately
-   Pipe output with $(...)

#### Complex exec workflows

Identify file types using the 'file' command on found files.

Code

Terminal window

```
# Convert image filesfind . -name "*.png" -exec convert {} {}.jpg \;
# Validate files before processingfind . -type f -exec sh -c 'head -c 4 "$1" | grep -q "^PDF" && echo "$1"' _ {} \;
# Parallel processing with GNU parallelfind . -name "*.log" | parallel gzip {}
# Backup and deletefind . -type f -mtime +365 -exec mv {} /backup/\; -delete
```

Execution

Terminal window

```
find /tmp -maxdepth 1 -type f -exec file {} \\; 2>/dev/null | head -2
```

Output

Terminal window

```
/tmp/session.log: ASCII text/tmp/cache.dat: data
```

-   Complex shell commands can follow -exec
-   Use sh -c for complex one-liners
-   GNU parallel for parallel processing

## Practical Examples

Real-world use cases and performance tips

### Real-World Use Cases

Common practical scenarios using find

#### Accessibility

Practical real-world examples

#### Best Practices

-   Always test find command before destructive operations
-   Use -mtime and size for cleanup operations
-   Monitor important directories regularly
-   Keep backups before bulk changes

#### Common Errors

-   **Backup failed or files missed:** Preview find output first, verify file count

#### Keywords

backupcleanupanalysismonitoringmaintenance

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Cleanup large old files

Find and list large log files older than 30 days for archiving or deletion.

Code

Terminal window

```
# Find and list large files modified long agofind /home -type f -size +100M -mtime +90 -exec ls -lh {} \;
# Archive old large filesfind /var/log -type f -size +10M -mtime +30 | tar czf archive.tar.gz --files-from=-
# Delete old temp filesfind /tmp -type f -mtime +7 -delete
# Cleanup disk space safelyfind . -type f \( -name "*.tmp" -o -name "*.bak" -o -name "*.log" \) -delete
```

Execution

Terminal window

```
find /var/log -maxdepth 1 -type f -mtime +30 -exec ls -lh {} \; 2>/dev/null | head -2
```

Output

Terminal window

```
-rw-r--r-- 1 root root 45M Feb 28 12:00 /var/log/syslog.1-rw-r--r-- 1 root root 23M Feb 28 10:00 /var/log/auth.log
```

-   Always use -mtime and size together for cleanup
-   Backup before making changes
-   Use -ls to preview before deletion
-   Monitor free space regularly

#### Project maintenance

Count total lines of Python code across project.

Code

Terminal window

```
# Find source files recursively, skip buildfind . -path "./build" -prune -o -path "./dist" -prune -o -type f -name "*.src" -print
# Count lines of codefind . -name "*.py" -exec wc -l {} + | tail -1
# Find files needing updatefind . -type f -name "*.js" -mtime +365
# Analyze code patternsfind . -name "*.py" -exec grep -l "TODO" {} \;
```

Execution

Terminal window

```
find /home -maxdepth 3 -name "*.py" -type f -exec wc -l {} + 2>/dev/null | tail -1
```

Output

Terminal window

```
1250 total
```

-   Prune build directories for accuracy
-   Use grep to find patterns in code
-   Monitor code metrics over time

#### Security and permissions audit

Find files with group or other write permissions (potential security issue).

Code

Terminal window

```
# Find SUID files (security risk)find / -type f -perm -u+s 2>/dev/null
# Find world-writable filesfind . -type f -perm -o+w
# Find files with unusual permissionsfind . -type f ! -perm 644
# Find recently modified system filesfind /etc -type f -mtime -1
# Find files with no ownerfind . -nouser
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f -perm /go+w 2>/dev/null | head -2
```

Output

Terminal window

```
/home/user/shared_file.txt
```

-   Audit SUID/SGID files regularly
-   Check for world-writable files
-   Monitor system file changes

#### Backup and synchronization

Count files modified in last day for backup purposes.

Code

Terminal window

```
# Find recent files for backupfind . -type f -mtime -1 | tar czf backup_today.tar.gz --files-from=-
# Identify changed filesfind . -mtime -7 -o -ctime -7
# Mirror directory with permissionsfind . -type f | cpio -p -d -v /backup/
# Create modification list for syncfind . -type f -printf "%T@ %p\n" | sort -n
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f -mtime -1 2>/dev/null | wc -l
```

Output

Terminal window

```
12
```

-   Use tar with --files-from for safe backup
-   cpio alternative for file copying
-   Sort by modification time for analysis

### Performance Optimization

Tips for efficient find usage on large filesystems

#### Accessibility

Performance optimization techniques

#### Best Practices

-   Always use -maxdepth to limit search depth
-   Prune heavy directories like node\_modules
-   Use -xdev to stay on one filesystem
-   Use + instead of \\\\; for batch operations

#### Common Errors

-   **Find is slow on large directories:** Use -maxdepth, -prune, and + batching

#### Keywords

performanceoptimizationspeedlargefilesystem

[Learn more](https://man7.org/linux/man-pages/man1/find.1.html)

#### Optimize find performance

Count files with limited depth and error suppression for faster execution.

Code

Terminal window

```
# Use -maxdepth to limit recursion depthfind . -maxdepth 3 -type f -name "*.py"
# Type first (most selective)find . -type f -name "*.log"  # betterfind . -name "*.log" -type f  # slower
# Prune large directories earlyfind . -path "*/node_modules" -prune -o -type f -print
# Suppress error messages to speed upfind . -name "*.js" 2>/dev/null
```

Execution

Terminal window

```
find /home -maxdepth 2 -type f 2>/dev/null | wc -l
```

Output

Terminal window

```
342
```

-   \-maxdepth reduces directory traversal
-   Type filter is very selective
-   \-prune skips entire directories efficiently
-   Redirect stderr (2>/dev/null) to hide permission errors

#### Filesystem-specific optimizations

Use -xdev to stay on same filesystem when searching /etc.

Code

Terminal window

```
# Find with NFS filesystem (use -noleaf)find /mnt/nfs -noleaf -type f -name "*.txt"
# Find local filesystem (use -xdev to skip other filesystems)find / -xdev -type f -name "config"
# Parallel find on large directoriesfind . -type d | parallel find {} -maxdepth 1 -type f
# Use locate for filename-only searches (fast)locate "*.py"  # much faster than find . -name "*.py"
```

Execution

Terminal window

```
find /etc -xdev -type f -name "*.conf" 2>/dev/null | wc -l
```

Output

Terminal window

```
23
```

-   \-noleaf for NFS mounted directories
-   \-xdev prevents crossing filesystem boundaries
-   locate database much faster for name-only searches
-   GNU parallel can distribute work across cores

#### Batch operations efficiently

Use + to batch files into one command for better performance.

Code

Terminal window

```
# Batch with + instead of separate calls with \;find . -type f -exec chmod 644 {} +    # fast: 1 process/callfind . -type f -exec chmod 644 {} \;   # slow: 1 process/file
# Use xargs with parallel executionfind . -type f -print0 | xargs -0 -P 4 rm
# Combine sort and processingfind . -type f -printf "%s %p\n" | sort -rn | head -10
# Process in batchesfind . -type f | head -100 | xargs tar czf batch1.tar.gz
```

Execution

Terminal window

```
find /tmp -maxdepth 1 -type f -exec ls -1 {} + 2>/dev/null | head -3
```

Output

Terminal window

```
/tmp/file1.txt/tmp/file2.log/tmp/file3.tmp
```

-   \+ batches multiple files (one process/batch)
-   \\\\; calls process for each file (slow)
-   xargs -P uses multiple parallel processes
-   Sort by size for analysis with -printf

Was this useful?

## Tags

#Find#File Search#Discovery#File Operations#Linux#Shell

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Ffind "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Find&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Ffind "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Ffind&title=Find&summary=Complete%20find%20reference%20with%20file%20searching%2C%20filtering%20by%20type%2Fsize%2Ftime%2C%20permissions%2C%20advanced%20operations%2C%20and%20practical%20examples%20for%20locating%20files&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Find%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Ffind "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Ffind&text=Find "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Ffind&title=Find "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Ffind&t=Find "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Ffind&media=&description=Complete%20find%20reference%20with%20file%20searching%2C%20filtering%20by%20type%2Fsize%2Ftime%2C%20permissions%2C%20advanced%20operations%2C%20and%20practical%20examples%20for%20locating%20files "Share on Pinterest")[Email](<mailto:?subject=Find&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Ffind>)

## Comments

## You might also enjoy

More posts on similar topics

## [Chmod](/cheatsheets/chmod)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   File Management
-   Tools

Complete chmod reference covering file permissions, recursive changes with -v and -c, reference mode, logical operators, batch operations, practical examples, and security best practices for Linux fil

#Chmod#Permissions#File Permissions+5 tags

[read more](/cheatsheets/chmod)

## [Grep](/cheatsheets/grep)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   Text Processing
-   Tools

Best practices for grep usageAlways quote patterns to prevent shell interpretation of special characters Use -E flag for complex patterns to avoid escaping issues with basic regex

#Grep#Search#Pattern Matching+3 tags

[read more](/cheatsheets/grep)

## [Sed](/cheatsheets/sed)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   Text Processing
-   Tools

This sed reference covers basic text substitution through advanced scripting techniques, with practical examples for text processing, file editing, and automation.

#Sed#Stream Editor#Text Transformation+3 tags

[read more](/cheatsheets/sed)

## [Cron](/cheatsheets/cron)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   System Administration
-   Linux
-   Scheduling
-   Automation
-   Tools

Quick reference Field layout Min Hour Day Month Weekday Command\* /path/to/command ┬ ┬ ┬ ┬ ┬ │ │ │ │ └───── Weekday (0=Sunday,

#Cron#Crontab#Scheduling+3 tags

[read more](/cheatsheets/cron)

## [Netstat](/cheatsheets/netstat)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   System Administration
-   Linux
-   Networking
-   Tools

This netstat cheatsheet covers six categories, with worked examples and troubleshooting steps in each.

#Netstat#Network#Connections+3 tags

[read more](/cheatsheets/netstat)

## [AWK](/cheatsheets/awk)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Text Processing
-   Linux
-   Command Line
-   Development Tools
-   Scripting

AWK complete reference guide Quick start Print entire file awk '{ print }' file.txt# Print specific column awk '{ print $1 }' file.txt# Print lines matching pattern awk '/patter

#AWK#Text Processing#Pattern Matching+3 tags

[read more](/cheatsheets/awk)

6 related posts
