rather new to unix. Trying to create a script to loop through all files and subdirectories given a directory and printing them. I would like to be able to skip certain directories dynamically though.

My idea was to create a for loop, for i in $(find ./ -printf '%f\n') as this will iterate through everything from the given directory, but I was curious if there was a way to skip over a directory if I came across one I didn't want to go down. As in

if [ "$i" == something I don't want to go down ] 
   skip this directory

Wasn't sure if it was possible. Found ways to skip directories using prune function but this requires you to know the types you want to skip beforehand, at least that was my understanding. Thanks.


Yes, -exec is a predicate just like -name, and find will consider the exit status of the command and treat it as false if it's non-zero.

But notice that a) this only applies to the -exec ... \; form, not to the -exec .. {} + form (which is always true) and b) forking a separate process for each file or directory is slow.

For example this will skip all directories that contain a file named foo.txt:

find . -type d -exec test -f {}/foo.txt \; -prune -or -print

$ mkdir -p a/{1,2,3}/{x,y,z}; touch a/{1,2,3}/{x,y,z}/a.txt
$ find . -type d -exec test -f {}/foo.txt \; -prune -or -print
... lots of files ...
$ touch a/{1,2}/foo.txt a/3/{x,y}/foo.txt
$ find . -type d -exec test -f {}/foo.txt \; -prune -or -print

Of course, instead of the test -f ... static command you can use eg. path/to/some/script {} .... With GNU find (the default in Linux) you can use -execdir instead of -exec.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.