I would like to change the ownership of all files and directories but exclude some directories:

find -user test ! -path "./dir1/*" ! -path "./dir2/*" -exec chown -R root:root {} \;

The ownership of the excluded directories is still changed?


  • 1
    You're missing an argument: the directory to start the find in. Since that defaults to ., if it happens to be owned by user test, it will match, and then you're recursively chowning everything under that anyway. – MadHatter Mar 28 '14 at 12:15

find . \( -path ./dir1 -o -path ./dir2 \) -prune -o -user test -exec chown root:root {} \;

Personally, for performance reasons, I prefer:

find . \( -path ./dir1 -o -path ./dir2 \) -prune -o -user test -print0 | xargs -0 chown root

| improve this answer | |
  • You have this backward. This will work only on dir1 and dir2. The OP want to work on everything except those two. – Sven Mar 28 '14 at 12:33
  • No. Doing -prune means exclude dir1 and dir2. The or (-o) means if you didn't prune them like you did with dir1 and dir2, then do the chown. – mlv Mar 28 '14 at 12:35
  • Yes, you are right. Anyway, this still includes the base dirs in the output and will chown them. – Sven Mar 28 '14 at 12:45
  • Yes, it includes . and other directories in . I thought that was asked. – mlv Mar 28 '14 at 12:55
  • What I meant was that ./dir1 and ./dir2 will still be listed by this and such chowned. It's not recursive anymore, but still. – Sven Mar 28 '14 at 13:01

Try this:

find . -user test | grep -v '^./dir1\|^./dir2' 

to check if the list is correct and

find . -user test | grep -v '^./dir1\|^./dir2' | xargs chown root:root

to do the rename.

| improve this answer | |

On Mac OS X you can use the following version of the command posted by Sven:

find . | grep -v '^./@R*' | tr \\n \\0 | xargs -0 chown root:root
| improve this answer | |

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.