Skip to content
Advertisement

How to skip multiple directories when doing a find

I’ve written a find function that searches for a string in each file in a given path, while skipping a list of directory names that I don’t want searched. I’ve placed this script in my .bashrc file to be called like so:

JavaScript

The find portion works great, and it colorizes the search text so that it visually stands out!, but I can’t get it to skip the directories listed with -prune. I’ve read all the posts here that I can find but none work for me. I’ve tried multiple variations with no luck. So I have a few questions:

  • How do you skip multiple directories?
  • How do you skip directories with just a partial name, such as those that begin with ‘–‘ or ‘wp-‘?
  • Can you mix -name and -path criteria in the same script?
  • Is there something else I’ve missed?

My server is CENTOS 6.9 virtuozzo with the bash shell.

JavaScript

Advertisement

Answer

A find expression is composed primarily of tests and actions joined together with operators. It is evaluated in a standard short-circuiting manner — meaning the evaluation is stopped as soon as the result is known, without the need to evaluate all parts (e.g. true or anything is evaluated to true).

Now note that -prune is an action that always returns true. It can act on the result of any test. Also note that the default operator is -a (and).

So, the simplest pruning example, to print all files except those under some path (e.g. wp-* in your example) looks like:

JavaScript

For files matching the path starting with ./wp-, prune action is executed, meaning the result is true, and the right part of the OR operator can be ignored (i.e. file is not printed). Note here that -path matches relative path, in this case rooted at ., so we have to write ./wp-* instead of wp-*.

To prune two paths, simply extend:

JavaScript

Here: if first prune action is not executed (result false), then a chance is given to the second, if that doesn’t prune neither (result false), then -print action is executed. In case any -prune gets evaluated, -print doesn’t get a chance.

Applying this to your case:

JavaScript

To avoid writing $1-dependent paths, you can cd "$1" and use f.e. find . ... -path ./logs ....

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement