How to Change File Ownership & Groups in Linux
File ownership and groups for files are fundamental to the Linux operating system. Every file in Linux is managed by a specific user and a specific group.
Figure out who owns the File, then use either chown or chgrp
Display ownership and group information using the following command:
ls –l file.txt
–rw–rw–r— 1 root www–data 0 Feb 25 15:51 file.txt
|
This file is owned by the root user and belongs to the www-data group.
Changing the Ownership of a File using chown
You can change the ownership of a specific file using the chown command. For security purposes only, the root user or members of the sudo group may transfer ownership of a file.
To change the ownership of a file:
chown rob file.txt
ls –l file.txt
–rw–rw–r— 1 rob www–data 0 Feb 25 15:51 file.txt
|
The file file.txt is now owned by Rob. By default, chown follows symbolic links and changes the owner of the file pointed to by the symbolic link. If you wish to change ownership of all files inside a directory, you can use the -R option.
chown –R user directory/
|
Changing the Group Ownership of a File using chgrp
All users on the system belong to at least one group. You can find out which groups you belong to using the following command:
groups username
|
You can then change the group ownership of a specific file using the chgrp command:
chgrp user file.txt
ls –l file.txt
–rw–rw–r— 1 rob user 0 Feb 25 15:51 file.txt
|
The file file.txt now belongs to the user group.
Changing Both the Owner and the Group using chown
You can change both the owner and group of a file using just the chown command.
chown user:test file.txt
ls –l file.txt
–rw–rw–r— 1 user test 0 Feb 25 15:51 file.txt
|
The file file.txt is now owned by user and belongs to the test group.