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.
2. Using the chown Command
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:
- –reference=Contaxt.txt – this option specifies the reference file, Contact.txt, whose ownership we want to clone
- Info.txt – represents the file whose ownership we want to change
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.
3. Using the chmod Command
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:
- rwx – gives the owner samuel read, write and execute permissions
- rw- – grants read and write permission to the members of the user group samuel
- r– – specifies that any other users can only read the 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.