Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
File ownership and permissions control who can access, change, and execute files and directories. This feature helps in maintaining the system’s integrity and security. Now, when working with files, it’s not uncommon to clone permissions and ownership from one file to another.
In this tutorial, we’ll explore cloning ownership and permissions from another file. To achieve this, we’ll use the chown and chmod commands in the command line.
In Linux, the chown command helps in changing the ownership of files and directories. So, every file and directory has an owner/user and belongs to a specific group.
To demonstrate, let’s compare two files:
$ ls -l
total 0
-rw-rw-r-- 1 samuel samuel 0 Ago 6 00:35 Contact.txt
-rw-rw-r-- 1 peter devs 0 Ago 6 00:35 Info.txt
In the above example, the owner of the Contact.txt file is samuel and it belongs to the group samuel. Whereas, the owner of the Info.txt file is peter and it belongs to the devs group.
Next, let’s clone ownership from the Contaxt.txt file:
$ chown --reference=Contact.txt Info.txt
In this example, we clone ownership from the Contact.txt file onto the Info.txt file:
Lastly, let’s see if the ownership cloning was successful:
$ ls -l
total 0
-rw-rw-r-- 1 samuel samuel 0 Ago 6 00:35 Contact.txt
-rw-rw-r-- 1 samuel samuel 0 Ago 6 00:35 Info.txt
At this point, we’ve managed to update the owner and group of the Info.txt file to match those of the Contact.txt file.
The chmod command allows us to change the permissions of files and directories. In detail, these file permissions, read, write, and execute, determine what actions can be performed on a file by the owner, group, and other users.
To begin, let’s check the file permissions of two different files:
$ ls -l
total 0
-rwxrw-r-- 1 samuel samuel 0 Ago 6 00:35 Contact.txt
-rw-rw-r-- 1 peter devs 0 Ago 6 00:35 Info.txt
By default, file permissions are grouped into three. To illustrate, let’s explain the permissions of the Contaxt.txt file:
Next, let’s clone permissions from the Contact.txt file onto the Info.txt file:
$ chmod --reference=Contact.txt Info.txt
Here, we also use the –reference option to declare the reference file from which the permissions will be cloned.
Finally, let’s confirm if we’ve succeeded:
$ ls -l
total 0
-rwxrw-r-- 1 samuel samuel 0 Ago 6 00:35 Contact.txt
-rwxrw-r-- 1 peter devs 0 Ago 6 00:35 Info.txt
From this output, we can see that we’ve managed to clone permissions from the Contact.txt file onto the Info.txt file.
In this article, we discussed how to clone ownership and permissions from one file to another. We achieved this by utilizing the chown and chmod commands from the command line.