Using chown to change ownership
September 28th, 2019
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. 😎
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.
bashmkdir dir1touch dir1/file2.txt
Now, let's take a look at the directory using the find command:
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.
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.
bashsudo useradd myuser1
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:
bashsudo chown myuser1 file1.txt
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:
bashsudo chown :myuser1 file1.txt
We can also change both the owner and group of a file in single command as shown here:
bashsudo chown myuser1:myuser1 newfile1.txt
🐠 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:
bashsudo chown -R myuser1:myuser1 dir1
chown can also be used to copy the owner/group permissions from one file to another:
bashsudo chown file1.txt --reference=/tmp/rootfile1.txt
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:
bashsudo chown -v user1:user1 file1.txt
all postsIn this article we learned about how the chown command can be used to control the ownership of a file or files. TaTa 👋