SH: Setting different file permissions for files and folders

As a sane person you'd like your file permissions to be different for files and for folders. But it's a bit of a pain to do this manually. But you don't have to!

tl;dr.

So what's the big issue?

Most of the time you'd like files to have mode 644: read and write for the owner and read for the group and others.

Folders are a bit different: they need to be executable to be able to enter them. This means that they need to have mode 755: read, write and execute for the owner, read and execute for the group and others.

Note: if you want your group to be able to access the files as well, you can use modes 664 and 775.

If you just use chmod 755 * you'll give both files and folders the same permissions. This is not what you want. Luckily there's the nifty find command!

Find searches through the given file path and returns the files it finds. Using its -type option you can easily specify for which type of file it needs to find: -type f for files and -type d for folders. Now you can use the -exec option of find to perform a command for each file it finds, like so: -exec chmod 755 {} \;. The {} part will insert the path of the file and the \; part will close the -exec statement.

Putting it all together

When you combine all of the above you get this:

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

Or as a one-liner:

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

Bonus

If you want your group ownership to be inherited for all files in a folder, meaning that a new file or folder in a folder owned by group "users" will also be owned by the group "users", you can use the following command:

find . -type d -exec chmod g+s {} \;