chown (Change Owner of File and Directory)
The chown
(CHange OWNer) command is used to change the owner of files or directories. With the -R
option, you can change the owner of all files and directories under the specified directory.
To demonstrate the chown
command, we'll create some directories and a file under the user_a home directory under superuser privileges.
cd /home/user_a
mkdir -p dir_a1/dir_a2
mkdir -p dir_b1/dir_b2
touch file_a
By running the commands above, you can create the following directory tree under the user_a's home directory.
user_a
├── dir_a1
│ └── dir_a2
├── dir_b1
│ └── dir_b2
└── file_a
Check owner statuses
As the directories and the file are created by the superuser, the owner and owner group of the directories and the file are set as root.
ls -l
total 8
drwxr-xr-x 3 root root 4096 Jan 2 15:31 dir_a1
drwxr-xr-x 3 root root 4096 Jan 2 15:31 dir_b1
-rw-r--r-- 1 root root 0 Jan 2 15:31 file_a
ls -l dir_a1
total 4
drwxr-xr-x 2 root root 4096 Jan 2 15:31 dir_a2
ls -l dir_b1
total 4
drwxr-xr-x 2 root root 4096 Jan 2 15:31 dir_b2
Change the owner of a file or directory
To change the owner of a single file or directory, you can simply run the chown
command without any options. For example, to change the owner of file_a to user_a, run the following command.
chown user_a file_a
Check the owner status of file_ a by running the ls -l
command. You can see that the file owner has changed to user_a.
ls -l file_a
-rw-r--r-- 1 user_a root 0 Jan 2 15:31 file_a
Change the owner of an entire directory recursively
To change the owner of an entire directory including sub-directory and files underneath, you can use the -R
option. For example, to change the owner of the directory tree of dir_a1 to usr_a, run the following command.
chown -R user_a dir_a1
Check the owner status of dir_ a1 and dir_a2 by running the ls -l
command. You can see that both directories' owners have changed to user_a.
ls -l
total 8
drwxr-xr-x 3 user_a root 4096 Jan 2 15:31 dir_a1
drwxr-xr-x 3 root root 4096 Jan 2 15:31 dir_b1
-rw-r--r-- 1 user_a root 0 Jan 2 15:31 file_a
ls -l dir_a1
total 4
drwxr-xr-x 2 user_a root 4096 Jan 2 15:31 dir_a2
Change the owner and group owner of an entire directory recursively
To change the owner and owner group at the same time, you can use the following syntax (add the group name followed by a user name with :
(colon).
For example, to change the owner and owner group of the directory tree of dir_b1 to user_a, run the following command.
chown -R user_a:user_a dir_b1
Check the owner status of dir_b1 and dir_b2 by running the ls -l
command. You can see that both directories' owners and owner groups have changed to user_a.
ls -l
total 8
drwxr-xr-x 3 user_a root 4096 Jan 2 15:31 dir_a1
drwxr-xr-x 3 user_a user_a 4096 Jan 2 15:31 dir_b1
-rw-r--r-- 1 user_a root 0 Jan 2 15:31 file_a
ls -l dir_b1
total 4
drwxr-xr-x 2 user_a user_a 4096 Jan 2 15:31 dir_b2