In this tutorial, we’ll look at how to recursively change file and directory permissions.
For an illustrative example, let’s create a test directory in the /home directory.
In the /home/test directory, create ten directories and in each of these directories ten files named from A to J:
mkdir -p test/dir{00..09} touch test/dir{00..09}/{A..J}
As you can see from the screenshot, the default permissions for directories are rwxr-xr-x or numerically 755. For files, the default permissions are rw-r—r— or numerically 644.
Chmod Recursive
The chmod command allows you to change file permissions in character or numeric mode.
To recursively work with all files and directories in a given directory, use the chmod command with the -R, (—recursive) option. The general syntax for recursively changing file permissions is as follows:
chmod -R MODE DIRECTORY
For example, to change the permissions for all files and subdirectories in the /home/test directory to 777, you would use:
chmod -R 777 /home/test
The permissions can also be specified using the symbolic method:
chmod -R u=rwx,go=rwx /home/test
Only the root user, file owner, or sudo user can change the file’s permissions. Be especially careful when changing file permissions recursively.
Using find command
Generally, files and directories should not have the same permissions. Most files do not need to execute permission, whereas you must set execute permissions on directories so that you can navigate to them.
The most common scenario is to recursively change the permissions for the website files 644 and the permissions for the directories 755.
Numerical method:
find /home/test -type d -exec chmod 755 {} \; find /home/test -type f -exec chmod 644 {} \;
Symbolic method:
find /home/test -type d -exec chmod u=rwx,go=rx {} \; find /home/test -type f -exec chmod u=rw,go=r {} \;
The find command searches for files or directories /home/test and passes each file or directory found to the chmod command to set permissions.
When using the find command with -exec, the chmod command is executed for each entry found. To speed up the operation, use the xargs command, passing multiple entries at once:
find /home/test -type d -print0 | xargs -0 chmod 755 find /home/test -type f -print0 | xargs -0 chmod 644
The chmod command with the -R options allows you to recursively change file permissions.
To recursively set file permissions based on file type, use chmod in conjunction with the find command.