Bash – Exclude a list of directories from unix find command

bashfind

I need to build a list of files present in a directory but also pass in a file containing a list of directories to exclude.

I've seen the below suggestion but I've had no luck with it when it comes to the type flag:

find $dir_name $(printf "! -name %s " $(cat $exclude_file))

Is there a way I can do it or will I need to create the entire list and then work through it removing ones that partially match ones in the exclude directory.

Best Answer

Given that your exclude_file contains paths, not names, you need to use -path to match its entries. To exclude matching directories’ subdirectories, you also need to -prune them. This should work:

find . -type d \( $(printf -- "-path */%s -o " $(cat "$exclude_file")) -false \) -prune -o -print

If you only want to see files, you can print only files:

find . -type d \( $(printf -- "-path */%s -o " $(cat "$exclude_file")) -false \) -prune -o -type f -print
Related Question