Find, chown and exclude directories

7,594

Solution 1

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

Solution 2

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.

Share:
7,594

Related videos on Youtube

timmanna
Author by

timmanna

Updated on September 18, 2022

Comments

  • timmanna
    timmanna almost 2 years

    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?

    Regards

    • MadHatter
      MadHatter over 10 years
      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.
  • FooBee
    FooBee over 10 years
    You have this backward. This will work only on dir1 and dir2. The OP want to work on everything except those two.
  • mlv
    mlv over 10 years
    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.
  • FooBee
    FooBee over 10 years
    Yes, you are right. Anyway, this still includes the base dirs in the output and will chown them.
  • mlv
    mlv over 10 years
    Yes, it includes . and other directories in . I thought that was asked.
  • FooBee
    FooBee over 10 years
    What I meant was that ./dir1 and ./dir2 will still be listed by this and such chowned. It's not recursive anymore, but still.
  • mlv
    mlv over 10 years
    It has the added bonus (when you use -print0 and xargs -0) of handling files with spaces in it.
  • mlv
    mlv over 10 years
    Did you try it? I did. It works fine. I did, in a directory, find . \( -path ./dir1 -o -path ./dir2 \) -prune -o -type d -print and all the directories where I was printed except dir1 and dir2.
  • FooBee
    FooBee over 10 years
    Yes, and here it prints the base names.
  • mlv
    mlv over 10 years
    What's your OS? I just tried it on OSX and Ubuntu 13.10 and it works fine.