Logo

How do I exclude a directory when using `find` in Linux?

To exclude a particular directory while searching with find, you can use a combination of -prune and -o (logical OR). For example:

find . -type d -name "excluded_dir" -prune -o -type f -name "*.txt" -print

Explanation

  1. -type d -name "excluded_dir" -prune: This tells find to skip (prune) any directory named "excluded_dir" instead of descending into it.
  2. -o (logical OR): Separates the prune condition from the actual search condition.
  3. -type f -name "*.txt" -print: The main search logic—here, it finds and prints all *.txt files.

As a result, excluded_dir is ignored, and find proceeds to look for text files in the rest of the directory tree. You can modify the pattern ("*.txt") or combine multiple conditions as needed.

More Complex Example

If you want to exclude multiple directories, you can chain pruning conditions:

find . \ \( -type d -name "node_modules" -prune \) -o \ \( -type d -name "vendor" -prune \) -o \ \( -type f -name "*.rb" -print \)

Here, both node_modules and vendor directories are skipped, and the command looks for Ruby files (*.rb) everywhere else.

Further Learning

To build a solid foundation in scripting, algorithms, and coding patterns, consider these courses from DesignGurus.io:

By understanding powerful Linux commands like find and strengthening your problem-solving skills, you’ll be well-prepared for both day-to-day development tasks and challenging coding interviews.

CONTRIBUTOR
TechGrind