Monday 27 March 2017

chown and chgrp commands examples

The command chown, an abbreviation of change owner, is used to change the owner of file system files, directories.
Actually the chown command can be used to change both user and group ownership, while the chgrp command can only be used to change group ownership.
CHOWN syntax
chown options user:group file/folder

Example:
1. Making john as the owner of the file1:
$ chown john file1
But the group owner will not be changed.

2. Changing ownership of multiple files:
$ chown john /path/to/file1 /path/to/file2 /path/to/file3

3. Change the owner and group  for a file.
$ chown john:artist file1

4. Using chown command on symbolic link file
When the chown command is issued on symbolic link to change the owner as well as the group then its the referent of the symbolic link whose owner and group will be changed by default. 
Using flag ‘-h’, you can forcefully change the owner or group of a symbolic link.
chown -h john:artist file_symlnk

5. Change owner only if a file already owned by a existing user
$ chown --from=john smith file

6. Change only group if a file has another group already present
$ chown --from=:artist :sports file1

7. Change owner and group using UID and GID
Use those UID and GID in place of new owner and group
$ chown 459:732 file1

8. Changing group to primary group.
$ chown john: file1
By default primary group is assigned to the file1if kept blankspace after:

9. Changing only group 
$ chown :artist file1

10. Copy the owner/group from one file to another using the ‘–reference’ flag
$ chown --reference=file1 newfile

CHGRP syntax
chgrp options groupname file/folder

Example:
1. Change the group  for a file.
$ chgrp artist file1

2. Changing group of multiple files:
$ chgrp artis /path/to/file1 /path/to/file2 /path/to/file3

3. Using chgrp command on symbolic link file
chgrp -h artist file_symlnk

4. Copy the group from one file to another using the ‘–reference’ flag
$ chgrp --reference=file1 newfile

5. To print the verbose messages only when changes made in file
$ chgrp -c artist file1

-R –recursive to operate on files and directories recursively
-v –verbose to output a diagnostic for every file processed