Copy Ownership from One File to Another on Linux

Copy Ownership from One File to Another on Linux

Managing file ownership is crucial on Linux, especially when dealing with multiple users, permissions, and system security. Every file and directory on Linux has an associated owner and group, which define who can read, write, or execute the file. Sometimes, you may need to change the ownership of a file to match another file, particularly when working with web servers, shared directories, or automated scripts. This tutorial explains how to copy ownership from one file to another on Linux.

First, create two files for testing:

touch main.txt other.txt

Assign ownership of main.txt to a specific user and group (e.g. www-data):

sudo chown www-data:www-data main.txt

Before changing ownership, verify the current owner and group of other.txt:

ls -l other.txt

Example output:

-rw-rw-r-- 1 john john 0 Mar 18 15:26 other.txt

Copy ownership from main.txt to other.txt:

sudo chown --reference main.txt other.txt

Check the ownership of other.txt again:

ls -l other.txt

Updated output:

-rw------- 1 www-data www-data 0 Mar 18 15:26 other.txt

Now, other.txt has the same owner and group as main.txt.

Leave a Comment

Cancel reply

Your email address will not be published.