Cloning Linux permissions and owner when cloning directories

Migrating file structures between Linux based hosts may sound like a very easy task and in most cases this is true, as it may just be about compressing the whole thing and using:

scp <host> <another_host>

However, there are some situations where this could be very painful task to complete, like when all your permissions accidently change!

A projects environment often requires different permission levels across different files and directories. When you migrate a complex file structure from one host to another, the migrated project’s file permissions may change in the new host, this case might happen for example if your first host is out of disk space and you can’t compress the project. In this article we’ll discuss a Linux Bash command that’s super useful in cases like these and we’ll use it in a test environment to prove the results.

In the following example we will see how to clone a directory from one path to another and then change the permissions, then we’ll see how to restore the proper permissions from the original directory. The following figure shows the directory for this test and its permissions.

Figure 1: Test_Dir permissions

Now let’s make another directory, the owner of the new directory will be the root user.

Figure 2: Test_Dir2 permissions and owner

After we create it, we’ll clone the permissions and owner of the first directory into the new directory. First, we’ll use the following command to clone the permissions from the reference and reflect them to the desired file or directory

sudo chmod --reference=test_dir test_dir2

We can see the result of the command in the following figure:

Figure 3: Cloned permissions successfully

Next let’s try to change the owner with the same reference as the one we used for permissions.

sudo chown --reference=test_dir test_dir2

Now lets check if the owner changed successfully.

Figure 4: Cloned owner successfully

Finally, This can be used with complex file structures with bash scripting depending on the situation and the specific objective that you want to achieve.

Doing DevOps and system administration stuff

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store