How to Copy File Permissions and Ownership to Another File in Linux?


Many times while taking back up of data from one location to another or configuring software, we need to maintain the same level of ownership and permission of the files. Creating those permissions and granting ownership to individual files can be error prone of done by typing commands for each of the files. So we use some arguments with the chown and chmod commands.

Ownership

We use the –-reference swiych in the chown function to specify the ownership cloning from the source file to the target file.

Syntax

chown --reference=source_reference_file target_file

In the below example we have a source file whose ownership gets cloned to the target file after executing the above command. The Ownership details are shown both before and after applying the command.

# Before cloning the ownership
$ ls –lt
# Applying the ownership
$sudo chown --reference=ref_file.txt all_rivers.txt
# After Applying the ownership
$ls -lt

Running the above code gives us the following result −

# Before applying ownership
-rw-r--r-- 1 root root 19 Jan 1 08:40 all_rivers.txt
-rw-rw-r-- 1 ubuntu ubuntu 2925 Jan 1 08:39 ref_file.txt
# After applying ownership
-rw-r--r-- 1 ubuntu ubuntu 19 Jan 1 08:40 all_rivers.txt
-rw-rw-r-- 1 ubuntu ubuntu 2925 Jan 1 08:39 ref_file.txt

File Permission

In a similar manner the file permissions also get copied from one file to another with a similar syntax, but involving chmod.

# Before cloning the permission
$ ls lt
# Applying the permission
$sudo chmod --reference=ref_file.txt all_rivers.txt
# After Applying the permission
$ls -lt

Running the above code gives us the following result −

# Before Cloning permission
-rw-r--r-- 1 ubuntu ubuntu 19 Jan 1 08:40 all_rivers.txt
-rw-rw-r-- 1 ubuntu ubuntu 2925 Jan 1 08:39 ref_file.txt
# After cloning permission
-rw-rw-r-- 1 ubuntu ubuntu 19 Jan 1 08:40 all_rivers.txt
-rw-rw-r-- 1 ubuntu ubuntu 2925 Jan 1 08:39 ref_file.txt

Updated on: 27-Jul-2023

765 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements