How to change file permissions for a directory in one command

unix

How can I change all the file permissions of a directory in one command in Unix?

Best Answer

To change permissions on a file or directory entry non-recursively, use the chmod command (see man chmod to read more about its specific options):

chmod +x dir  # Set a directory to be listable
chmod +x file # Set a file to be executable

To change the owner of a file/directory recursively (affecting all descendants):

chown -R username           dir # Recursively set user
chown -R username:groupname dir # Recursively set user and group

To change permissions bits of all files in a directory, recursively:

find dir -type f -exec chmod 644 {} ';' # make all files       rw-r-r-

To change permissions bits of all directories:

find dir -type d -exec chmod 755 {} ';' # make all directories rwxr-xr-x

It would be nice if you could just do this:

chmod -R 755 dir

However, this has problems. It treats files and directories the same. The above command makes directories listable and readable by all users, but it also makes all files executable, which is usually what you do not want to do.

If we change it to 644, we get another problem:

$ chmod -R 644 x2
chmod: cannot access `x2/authors.html': Permission denied
chmod: cannot access `x2/day_of_week.plot': Permission denied
chmod: cannot access `x2/day_of_week.dat': Permission denied
chmod: cannot access `x2/commits_by_year.png': Permission denied
chmod: cannot access `x2/index.html': Permission denied
chmod: cannot access `x2/commits_by_year.plot': Permission denied
chmod: cannot access `x2/commits_by_year_month.plot': Permission denied
chmod: cannot access `x2/files_by_date.png': Permission denied
chmod: cannot access `x2/files.html': Permission denied
...

The problem is that 644 takes out the directory list bit, and this side effect prevents further traversal of the file tree. You could work around this issue by using sudo, but you still end up with directories that are completely useless to non-root users.

The point is, chmod -R works just fine in some cases (e.g. chmod -R g-r), but not in cases where you want to mess with the -x bit, since it operates on files and directories indiscriminately.

Related Question