How to recursively change the File’s Permissions using chmod and find in Linux
The syntax for recursively changing the file permission using chmod command is:
chmod -R [permission] [directory]
For eg, sudo chmod -R 755 test-directory
The syntax using the find command to locate files/directories and then passing it on to chmod to set the permission:
Using the numeric method:
find <location> -type d -exec chmod 755 {} \;
find <location> -type f -exec chmod 644 {} \;
For eg,
find /var/www/html -type d -exec chmod 755 {} \;
find /var/www/html -type f -exec chmod 644 {} \;
Using the symbolic method:
find <location> -type d -exec chmod u=rwx,go=rx {} \;
find <location> -type f -exec chmod u=rw,go=r {} \;
For eg,
find /var/www/html -type d -exec chmod u=rwx,go=rx {} \;
find /var/www/html -type f -exec chmod u=rw,go=r {} \;
If you use the find command with -exec, the chmod command will run for each found entry.
You can use the xargs command to speed up the operation by passing multiple entries at once:
For eg,
find /var/www/html -type d -print0 | xargs -0 chmod 755
find /var/www/html -type f -print0 | xargs -0 chmod 644
The syntax for changing the permission of a specific file type in a directory is:
find [directory] -name "*.[filename_extension]" -exec chmod [privilege] {} \;
For eg,
find . -name “*.txt” -exec chmod +x {} \;