In our find command primer we covered a lot of information. However, it was impossible to cover everything. In this Linux quick tip we will discuss how to exclude directories from find searches.

Let's use the following directory structure as an example. Here we have a Recipes folder which contains three regions Indian, Italian, and Thai. Each of these directories has recipes inside of them. All of then contain a rice.txt file.

├── Indian
│   ├── baati.txt
│   ├── chaat.txt
│   └── rice.txt
├── Italian
│   ├── arancini.txt
│   ├── ciabatta.txt
│   ├── muffuletta.txt
│   ├── ragu.txt
│   └── rice.txt
└── Thai
    ├── Phat-Thai.txt
    └── rice.txt

3 directories, 10 files

If we did a search for rice.txt with the find command, it would return all three files.

[mcherisi@putor Recipes]$ find . -name rice.txt

Don't Search Specific Directory with Find

Let's say we wanted to exclude the Italian directory from our search. We can use the not (!), path (-path) and prune (-prune) options like so.

[mcherisi@putor Recipes]$ find . ! \( -path ./Italian -prune \) -name rice.txt

This successfully excluded find from searching inside the Italian directory.

Let's break down the command to better understand it. The command starts with find followed by a ., which means current directory. This is followed by the ! which means "not" which can also be written as -not. Then we have an expression enclosed in parenthesis, which forces precedence. Inside the parenthesis is -path followed by the path we want to exclude. The -prune means if the expression is a directory, do not search inside of it. Then we end the -name followed by the name of the file we are searching for.

Exclude Multiple Directories from Find Searches

The part of the command that excludes a directory from being search is:

! \( -path ./Italian -prune \)

To exclude multiple directories, simply duplicate the above code. In the next example we exclude both Italian and Thai directories from being searched.

[mcherisi@putor Recipes]$ find . ! \( -path ./Italian -prune \) ! \( -path ./Thai -prune \) -name rice.txt


Now you should be comfortable enough to exclude directories from your find command searches. I used this often because my system has two very large drives with 4+ TB of data mapped to it. When I do a regular find from root it would also search these drives since they are mounted under root.

It may seem daunting at first, but once you understand the operators and expressions used it becomes clear. To learn more about the find command use the links in the resources section below.