To exclude a directory when using the find command in Linux, use the -prune option to prevent find from descending into specific directories. Here’s how to do it:
Basic Syntax
find /path/to/search \( -name "directory_to_exclude" \) -prune -o [options/actions]
-name "directory_to_exclude": Matches the directory you want to skip.-prune: Tellsfindnot to traverse into the matched directory.-o: Logical “OR” operator to combine conditions.
Examples
1. Exclude a Single Directory
Exclude the node_modules directory when searching for files:
find . -name "node_modules" -prune -o -print
2. Exclude Multiple Directories
Exclude both logs and cache directories:
find /var \( -name "logs" -o -name "cache" \) -prune -o -print
3. Search for Files While Excluding a Directory
Find all .txt files but skip the backup directory:
find /home -name "backup" -prune -o -name "*.txt" -print
4. Exclude a Directory by Path
Exclude an absolute path like /home/user/temp:
find /home -path "/home/user/temp" -prune -o -print
5. Combine with Other Actions
Delete all files except those in the protected directory:
find . -name "protected" -prune -o -type f -delete
Key Notes
- Grouping Conditions: Use
\( ... \)to group multiple exclusion conditions. - Case Insensitivity: Use
-inameinstead of-namefor case-insensitive matching. - Wildcards: Use wildcards (e.g.,
*.log) to exclude patterns.
Alternative: Use -not -path (Less Efficient)
This checks every file path, which is slower than -prune:
find . -not -path "./exclude_dir/*" -print
Summary
| Scenario | Command |
|---|---|
| Exclude one directory | find . -name "dir" -prune -o -print |
| Exclude multiple directories | find . \( -name "dir1" -o -name "dir2" \) -prune -o -print |
| Exclude by path | find . -path "./dir/*" -prune -o -print |
| Case-insensitive exclusion | find . -iname "DirName" -prune -o -print |
Use -prune to efficiently skip directories and avoid unnecessary traversal!