How to Change the File Owner and Group in Linux

In Linux, every file and directory is managed by a specific user and a specific group. File system ownership is fundamental to the Linux operating system’s security and access control. Please note that only the root user or members of the sudo group can change the ownership of a file in Linux for security purposes.

How to Change the File Owner and Group in Linux

For instance, let’s say we have a file named file.pdf. We want to change the ownership of this file to a user named santhosh and also change the group ownership of this file to a group called digitash. Let’s see how to do just that.

Find the Current File Owner and Group

You can find the current owner and group of the file by using the ls -l command:

sudo ls -l file.pdf

You will get an output that looks like this:

-rw-rw-r-- 1 root www-data 1847 Oct 9 2019 file.pdf

This means that the file is currently owned by the root user and belongs to the www-data group.

Change the File Owner of a Specific File

You can change the file owner using the chown command:

sudo chown santhosh file.pdf

Check if the file owner has been changed:

sudo ls -l file.pdf
-rw-rw-r-- 1 santhosh www-data 1847 Oct 9 2019 file.pdf

You will now see that the file ownership has been successfully updated.

Change the Ownership of All Files Inside a Directory

To change the ownership of all files inside a directory recursively, you can use the -R option as follows:

sudo chown -R user directory/

Change the Group Ownership of a Specific File

You can change the group ownership of a specific file using the chgrp command:

sudo chgrp digitash file.pdf

Verify the change:

sudo ls -l file.pdf
-rw-rw-r-- 1 santhosh digitash 1847 Oct 9 2019 file.pdf

Change the Group Ownership of All Files Inside a Directory

To change the group ownership of all files inside a directory recursively, use the -R option:

sudo chgrp -R group directory/

Change Both the File Owner and the Group Simultaneously

You can change both the file owner and the group at the same time using just the chown command by separating the user and group with a colon:

sudo chown santhosh:digitash file.pdf

Verify the final changes:

sudo ls -l file.pdf
-rw-rw-r-- 1 santhosh digitash 1847 Oct 9 2019 file.pdf

Leave a Reply

Your email address will not be published. Required fields are marked *