Set permissions on files equal to another directory in linux

In this example, I want to make the owners and permissions of files in the current directory equal to the same file in another directory.

This is the scenario:

  1. I am in /tmp/dir1
  2. I want to set the permissions and owners on every file in the current directory to be equal to the same file in /tmp/dir2/path/to/same/file
root@linux# cd /tmp/dir1
root@linux# find ../dir2 -exec stat -c "%a %g %u %n" {} \; | \
while read mode user group file; \
do chown $user:$group ${file/\.\.\/dir2/.} && \
chmod $mode  ${file/\.\.\/dir2/.}; done

What happens here:

  1. find all file in /tmp/dir2 and give me the owners and permissions
  2. place the permissions and owners in the following variables: mode, user, group and file
  3. change the owner and the permissions on every found file

 

Notice that in step 3 I do a find/replace inside the value of variable $file. I want to replace the text ‘../dir2‘ with ‘./‘.
This way, I change the found file
‘../dir2/wp-content/themes/twentythirteen/style.css‘ into our local file:
‘./wp-content/themes/twentythirteen/style.css‘ .

You could also save the permissions and owners for every file in another file so you can use that as a reference for later use:

# find ../dir2 -exec stat -c "%a %g %u %n" > permissions.log

 

0 Shares

Leave a Reply

Your email address will not be published. Required fields are marked *