Skip to content
Advertisement

How to limit a search of a directory with “find” command?

I am trying to make a Bash script that would create symlinks to directories that have a “target” subdirectory. I use “find” command to search for the “target” directories and put the filepaths to array.

JavaScript

The array is looped through and symbolic links are made to directories. My issue is that the depth of the directory structure is unknown and the subdirectories can have multiple “target” directories.

The directory structure could be:

JavaScript

At the moment these paths are found and there are unwanted symbolic links created.

JavaScript

How could I limit that when the “target” is found the search will not continue further into the subdirectories?

Advertisement

Answer

The shortest solution first, even if it was found at last (suggested by Eastman himself in a comment).

JavaScript

With the -path option, you may exclude paths, containing the whole token “/target/”. In contrast to -name, which only evaluates the filename itself, the path needs globbing to catch foo/target and target/bar. And of course it needs negation -not -path “/target/“.

JavaScript

With a test on my system and foo instead of target:

JavaScript

The option -path … -prune seems to have the same effect. For detailed differences, please study the manual carefully. A short test revealed a 10% time benefit by using prune, but it can be a caching effect or random influence.

(needlessly verbose intermediate solution:)

find -type d -name “foo” -path “/foo” -prune

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