Thursday, November 6, 2008

Combined find, xargs and chown Trick

Sometimes, you want to change the ownership of files (including symlinks) in directories recursively. However, "malformed" directory and file names can become huge stumbling blocks. This is how to do that correctly:

root@copy_cabana# find . -user old_user -group old_group -print0 | xargs -0 chown -v -h new_user:new_group

A few notes:


  • The -print0 parameter tells find to append the "null" character after each matching filename instead of the usual "newline" character. This is handy to "fight" against malformed filename and directory name that contain white spaces, punctuation, etc.


  • The -0 parameter tells xargs that the delimiter in its input is not "newline" but a "null" character.


  • The -h parameter tells chmod to change the ownership of the symlink instead of the file/directory the symlink refers to.




That's it. Now you're prepared for weird filenames.
Post a Comment

3 comments:

sn8k said...

Thanks for this! Bad file names were killing it for me and this solved it!

Darmawan Salihun said...

happy that you find the use for that trick. It was from deep down the "find manual"

chambers said...

This command has been invaluable to me over the years. Thanks!