Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Copy File Permissions and Ownership to Another File in Linux?
When backing up data or configuring software in Linux, you often need to maintain the same ownership and permissions across files. Instead of manually setting permissions for each file, Linux provides efficient methods to copy these attributes from one file to another using the chown and chmod commands with the --reference option.
Copying File Ownership
Use the --reference switch with chown to copy ownership from a source file to a target file ?
Syntax
chown --reference=source_file target_file
Example
Let's copy ownership from ref_file.txt to all_rivers.txt ?
# Check current ownership $ ls -lt # Copy ownership from ref_file.txt to all_rivers.txt $ sudo chown --reference=ref_file.txt all_rivers.txt # Verify the change $ ls -lt
The output shows ownership being copied ?
# Before copying 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 copying 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
Copying File Permissions
Similarly, use chmod with --reference to copy permissions from one file to another ?
Syntax
chmod --reference=source_file target_file
Example
# Check current permissions $ ls -lt # Copy permissions from ref_file.txt to all_rivers.txt $ sudo chmod --reference=ref_file.txt all_rivers.txt # Verify the change $ ls -lt
The output demonstrates permission copying ?
# Before copying permissions -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 copying permissions -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
Key Points
- The
--referenceoption eliminates the need to manually specify numeric permission codes - Both commands require
sudowhen changing ownership or permissions of files owned by other users - You can copy both ownership and permissions separately as needed
- This method is particularly useful for batch operations and automation scripts
Conclusion
The --reference option with chown and chmod provides an efficient way to copy file ownership and permissions. This approach reduces errors and saves time when managing multiple files with identical access requirements.
