Saturday, January 29, 2011

How to apply CHMOD command to any file with a specific name recursively in Linux?

I need to know how to apply a CHMOD command to only files that have a specific name recursively?

chmod 755 -R filename

Something like above but it should apply to any filename that exists in any sub folders.

  • This will find all files named filename, recursively from the current directory, and pass them to chmod.

    find -name filename | xargs chmod 755
    

    See the manpages for find and xargs for more advanced options. In particular, look at the -print0 flag and corresponding -0 to xargs if you get errors about files with spaces in the name.

    From calmh
  • There's also a exec parameter in find that will do the same:

    find . -name filename -exec chmod 755 {} \;
    
    packs : The trade off here is execution efficiency. Xargs will only call chmod approximately the minimum number of times necessary for the number of files, the exec option to find will call it once for each file found.
    Dennis Williamson : However, if your version of `find` supports it, you can use a `+` instead of the `\;` to get `xargs`-like functionality.
    From Dave Core
  • You can get the best of both worlds if you use the + operator to find to make it run chmod on many files at once.

    find . -name filename -exec chmod 755 '{}' +
    

    You should always put a ' around your {}, otherwise a filename with a space in it could mess things up. In this case it's not a problem, but I have a habit of doing it.

0 comments:

Post a Comment