Using chown to change ownership

File ownership is fundamental in Linux. Every file is associated with an owner and a group, which is something we can change using the chown command.

File permissions govern who can read, write to, and delete file on a computer.
In this article, we will see how to use the Linux 🐧 chown to control file permissions. 🤩
A basic familiarity with Linux and the command line would help, but is not required.

To understand how chown works, you just have to follow the instructions below.

First, we need to open our Linux terminal 🔋, I'm using WSL (Windows Subsystem for Linux) with Ubuntu config you can use any terminal config of your choice. 😎

img

For now our directory is empty, let's create something to work on with. You can use mkdir to create a directory and touch to create a file.

bash
mkdir dir1
touch dir1/file2.txt
img

Now, let's take a look at the directory using the find command:

bash
find .
img

Just a single directory and a file in it. Now let's get started learning about chown! 🤑

First, let's create a file named file1.txt in the current directory.

bash
touch file1.txt
img

Now, create a user named myuser1 and check the ownership of file1.txt using ls -l, use sudo for administrative privileges and enter your password.

bash
sudo useradd myuser1
img

We can see that the current owner of the file is majhi_rockzz and it belongs to the majhi_rockzz group.

The owner and group name can be different in different machine eg. root, sumit_lappy, sagar_pc etc.

Let's change the ownership of file1.txt to myuser1:

bash
sudo chown myuser1 file1.txt
img

Using ls -l, you can see that the owner of file1.txt has changed to myuser1.

If we want to change the group of a file, we can do that also using chown:

bash
sudo chown :myuser1 file1.txt
img
We can also change both the owner and group of a file in single command as shown here:
bash
sudo chown myuser1:myuser1 newfile1.txt
img

🐠 If we wish to recursively change ownership of a directory and its content, we can do it by passing the -R (recursive) flag to chown. Let's do that now with:

bash
sudo chown -R myuser1:myuser1 dir1
img

chown can also be used to copy the owner/group permissions from one file to another:

bash
sudo chown file1.txt --reference=/tmp/rootfile1.txt
img

If you ls -l the current directory, you'll see that file1.txt now belongs to majhi_rockzz again.

Finally, if you wish to list the changes made by the chown command in a verbose manner, we can do so using this command:
bash
sudo chown -v user1:user1 file1.txt
img

Wrapping Up

In this article we learned about how the chown command can be used to control the ownership of a file or files. TaTa 👋
all posts

Made with 🤎 by Sumesh Majhi