How can I exclude a specific directory when using the `find` command in Linux?

I’m using the Linux find command to search for files, and I’m trying to figure out how to find exclude directory results cleanly.

For example, I want to search for all JavaScript files starting from the current directory, but I don’t want find to descend into a particular folder (like a dependencies or build directory).

Here’s the basic command I’m currently using (rewritten example):

find . -name "*.js"

This works, but it searches every subdirectory, including ones I’d prefer to skip.

What’s the correct way to exclude a specific directory from the search while still finding all matching files elsewhere? Are there any common patterns or best practices for excluding one or more directories when using find?

Any help or examples would be appreciated. Thanks!

I’ve had this problem before, and the trick that worked for me is using -prune. It basically tells find not to descend into the specified directory. For example, if you want to skip a folder named node_modules while looking for .js files, you can do:

find . -path "./node_modules" -prune -o -name "*.js" -print

Here, -prune prevents find from going into node_modules, and the -o says “or,” so the rest of the command (-name “*.js” -print) still executes for all other directories. It’s a little tricky at first, but once you get the order right, it works reliably.

I ran into a similar situation when I had to skip several folders. You can combine -prune with parentheses and -o to exclude multiple directories. For example:

find . \( -path "./node_modules" -o -path "./build" \) -prune -o -name "*.js" -print

This way, both node_modules and build are skipped. I found this pattern very useful for large projects where you don’t want to waste time searching in vendor or temporary directories.

Sometimes I just let find find everything and then filter out paths I don’t want using grep -v. It’s simpler for quick one-off searches:

find . -name "*.js" | grep -v "./node_modules/"

This isn’t as efficient for huge trees because find still visits the excluded directories, but it’s easier to remember and works well for small projects or scripts.