r8dhex dot net

photos, code, and hardware

© r8dhex

Recursively chmod'ing directories and files

I'm writing this down, since I often encounter this use-case, and I don't want to forget it.

Sometimes you find a directory, e.g. all of your music, where all the permissions are a mess. You have some files that are owned by you, and some by root, and some by another user ID from a previous installation. Some are read-only, some are read-write and various other combinations. You just want to set them all to be owned by you, read-write, but readable by anyone who has an account on your machine.

Assuming you have root access, this is pretty easy. And easy to mess up, so be very careful.

So first thing you do is this:

chown -R you:yourgroup *

If you were in the correct directory, it would set all the files and directories under the current one, to be owned by you and yourgroup.

For permissions, it's a bit trickier. The first thing that comes to mind is:

chmod -R 644 *

...which is similar to the chown command. You set everything in the driectory and below to be RW by the owner, in this case "you", and R by group and others.But what about directories? For directories, the RWX permissions work a bit differently:

  • Read - grants the ability to read the names of files in the directory
  • Write - grants the ability to modify entries in the directory. This includes creating files, deleting files, and renaming files.
  • Execute - grants the ability to traverse its tree in order to access files or subdirectories, but not see files inside the directory.

If you set RW on a directory, theoretically you would only be able to list the files, and to create, read and rename. But since you can't get into the directory without the X, you actually can't do anything.So you can't use a recursive chmod on a directory tree, since you need different permissions depending on if the file was a directory or an actual file. You typically need 644 for files, and 755 for directories.These 2 lines apply chmod only to the appropriate types:

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

The first one applies to directories, and the second applies to files. Make sure you don't forget the "+" at the end, this tells find to try to call chmod as little as possible. You can change the permissions to whatever suits you.