Linux / UNIX: Change File Permissions Recursively ( conditional )

Get real time updates directly on you device, subscribe now.

How do I recursively change files with 777 permissions to 755 in /home/user/demo directory? I have a number of files in this directory and I need to change permission from 0777 to only if that file has 777 permissions. Is there an easy way out to achieve this on a Linux or Unix-like systems?

To change file access permissions you need to use the chmod command. It has -R or –recursive option that change files and directories recursively. [donotprint][/donotprint]The find command can be used to find files and directories. The chown command can be used to change user and group permission.

chmod Command Examples

In this example, you are setting permission to 0755:
$ chmod -R 0755 directoryNameHere
However, if you need to apply conditional file permissions recursively, you need to use combination of the find and chmod command. To find all files in /home/user/demo directory, enter:
$ find /home/user/demo -type f -print
To find all files in /home/user/demo directory with permission 777, enter:
$ find /home/user/demo -type f -perm 777 -print
Finally, apply new permission using the -exec option as follows:
$ find /home/user/demo -type f -perm 777 -print -exec chmod 755 {} ;
To select directories and subdirectories use the following syntax:

$ find /var/www/html -type d -perm 777 -print -exec chmod 755 {} ;

Sample Shell Script To Change Permission Recursively

# Purpose: Set correct webserver files and dir permissions
# Author: SXI ADMIN < [email protected] >
# This script is released under GPL version 2.0 or above
# Set root permission as follows for the Apache / Lighttpd / Nginx DocumentRoot
# + Dirs/Subdirs: read-only and execute to others
# + Files: read-only permission
# Tested on Debian Linux v3/4/5/6 and RHEL v2/3/4/5/6
# -------------------------------------------------------------------------------------------------
echo "I will change the file permission for webserver dir and files to restrctive read-only mode for "$_dir""
read -p "Your current dir is ${PWD}. Are you sure (y / n) ?" ans
if [ "$ans" == "y" ]
	echo "Changing file onwership to $_ugperm for $_dir..."
	$_chown -R "${_ugperm}" "$_dir"
	echo "Setting $_fperm permission for $_dir directory...."
	$_chmod -R "${_fperm}" "$_dir"
	echo "Setting $_dperm permission for $_dir directory...."
	$_find "$_dir" -type d -print0 | $_xargs -0 -I {} $_chmod $_dperm {}

You can run this script as follows:
./script /var/www/html/
./script /usr/lib/cgi-bin/

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Get real time updates directly on you device, subscribe now.