Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing chmod for files but not directories

Tags:

grep

unix

chmod

I need to use chmod to change all files recursivly to 664. I would like to skip the folders. I was thinking of doing something like this

ls -lR | grep ^-r | chmod 664 

This doesn't work, I'm assuming because I can't pipe into chmod Anyone know of an easy way to do this?

Thanks

like image 873
Ori Avatar asked Jul 22 '09 05:07

Ori


2 Answers

A find -exec answer is a good one but it suffers from the usually irrelevant shortcoming that it creates a separate sub-process for every single file. However it's perfectly functional and will only perform badly when the number of files gets really large. Using xargs will batch up the file names into large groups before running a sub-process for that group of files.

You just have to be careful that, in using xargs, you properly handle filenames with embedded spaces, newlines or other special characters in them.

A solution that solves both these problems is (assuming you have a decent enough find and xargs implementation):

find . -type f -print0 | xargs -0 chmod 644 

The -print0 causes find to terminate the file names on its output stream with a NUL character (rather than a space) and the -0 to xargs lets it know that it should expect that as the input format.

like image 53
paxdiablo Avatar answered Oct 24 '22 11:10

paxdiablo


Another way to do this is to use find ... -exec ... as follows:

find . -type f -exec chmod 644 {} \; 

The problem is that the -exec starts a chmod process for every file which is inefficient. A solution that avoids this is:

find . -type f -exec chmod 644 {} + 

This assembles as many file names arguments as possible on the chmod processes command line. The find ... | xargs ... approach is similar; see the accepted answer.

For the record, using back-ticks is going to break if there are too many files to be chmoded, or the aggregated length of the pathnames is too large.

like image 43
Stephen C Avatar answered Oct 24 '22 10:10

Stephen C