In a directory I want to delete certain sub-directories while excluding others. Some by owner and some by name. I have configured per man page, but no files are deleted, even those not expressly excluded . While testing If I remove all the exclude parameters then all all the files are deleted as you would expect. I get no error when I run it, just nothing happens. Would appreciate a review of the script. Names changed to protect the innocent.

find /nobackup/. -name '*' -type d ! -user 'foo' \! -user 'foo1' ! -user 'foo2' ! -user 'foo3' \! -user 'foo4' ! -name 'acmecache' -delete

I would add -depth so that trees of files can be deleted in one pass. The -name '*' is irrelevant.

Your description says you want to delete certain directories. The -delete will only delete empty directories. Your code as written will happily descend into the acmecache directory and remove any directories there that aren't owned by the_foo*_ users. I'm going to assume that's not what you intended, so you need to use -prune.

Try this instead. Remove the echo when you're happy with the result

find /nobackup -depth -type d \( \( -user 'foo' -o -user 'foo1' -o -user 'foo2' -o -user 'foo3' -o -user 'foo4' -o -name 'acmecache' \) -prune \) -exec echo rm -rf {} \;
  • Testing this script, nothing was deleted. Test environment is 3 directories. One owned by me, listed In the script with an –o flag, one owned by a user not listed in the script with an –o flag, and the acmecache directory owned by root. When I run the script the directory owned by the user not listed in the script with an –o flag doesn’t show in the stdout, but the rest of the directories do and no directories or files within them are deleted. – John Jan 11 '16 at 18:55
  • @John did you read my advice to remove the echo when you were happy the command was going to do what you expected? – roaima Jan 11 '16 at 19:14
  • Yes I did, thank you. The issue is that directories owned by users not called out in the script are not being deleted. – John Jan 11 '16 at 22:56

The script seems correct.

What it does is the following: delete all directories under /nobackup and below that do not belong to foo users, excluding also the directories called acmecache.

The -name '*' argument seems completely unnecessary.

Also consider that the -delete only removes empty directories. But will print an error if the directory is not empty.

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.