Linux – Find directories that do not contain a directory

bashcommand-line-interfacefindlinux

I'm trying to figure out how to use the linux "find" command (or another command that will get the job done) to return a list of file paths/directories that do not contain a directory of a certain name.

~/web/domain1.com/public_html/bar
~/web/domain2.com/public_html/
~/web/domain3.com/public_html/bar
~/web/domain4.com/public_html/

I want all of the paths that don't contain the directory named "bar" (domain2.com and domain4.com). Any idea how I can get find to output such a list?

Thanks!

Best Answer

find ~ -type d '!' -exec test -d '{}/bar' ';' -print

... but this probably isn't exactly what you want; for the example directories you gave, it'll output:

/path/to/home
/path/to/home/web
/path/to/home/web/domain1.com
/path/to/home/web/domain1.com/public_html/bar
/path/to/home/web/domain2.com
/path/to/home/web/domain2.com/public_html
/path/to/home/web/domain3.com
/path/to/home/web/domain3.com/public_html/bar
/path/to/home/web/domain4.com
/path/to/home/web/domain4.com/public_html

i.e. it lists every directory that doesn't contain a "bar" subdirectory, including even the "bar" directories themselves (unless they contain their own bar subdirectories...). You probably want to add an additional restriction, like only listing directories at a certain depth:

find ~ -type d -depth 3 '!' -exec test -d '{}/bar' ';' -print

or with a certain name:

find ~ -type d -name public_html '!' -exec test -d '{}/bar' ';' -print

...both of which print:

/path/to/home/web/domain2.com/public_html
/path/to/home/web/domain4.com/public_html