05. Changing file owner and group chown, chgrp, -R

To change the owner and group owner of a file or directory, we use chown (short for change owner). To change a new group, use the similar command chgrp.

We must have root permissions to use this command.

Syntax

The syntax for chown is as follows:

$ chown [options] [owner]:[group] files

The syntax for chgrp is very similar:

$ chgrp  [options] newgroup files

Examples

Here are some functionalities of chown and chgrp that are used in the real world.

1) Changing file owner

To change the file owner, specify the user, then the file name.

$ chown bob sampleFile.txt

The sampleFile.txt file will change user to bob.

2) Changing the group

To change the file's group owner, we set the group name after a colon (:). This provides the same function as chgrp command.

$ chown :programmers todo-list.txt
$ chgrp programmers todo-list.txt

3) Changing both file and group ownership

$ chown bob:redditors sampleFile.txt

Here, we are changing the sampleFile.txt. The argument before the : indicates the new user, while the argument after shows the new group.

4) Recursive subdirectories and files with -R

To recursively grant ownership of a directory and all files with subdirectories within, use the -R option.

$ chown -R bob /files/folder

An example to wrap things up

Let's go through an example with two users: marie and bob.

marie has access to sudo commands, and wants to copy a file into bob's home directory. She would like to give bob the ownership.

$ sudo cp sampleFile.txt ~bob
Password:
# Copied file to bob's homepage.
$ sudo ls -l ~bob/sampleFile.txt
-rw-r--r-- 1 marie staff 2014-01-13 16:00 /home/bob/sampleFile.txt
# bob only has read access to this file.
$ sudo chown bob: ~bob/sampleFile.txt
-rw-r--r-- 1 bob bob 2014-01-13 16:00 /home/bob/sampleFile.txt
# Now bob has ownership and has write access.

Take your Linux skills to the next level!

Linux for Beginners

Take your Linux skills to the next level! Try Linux & UNIX

Linux for Beginners doesn't make any assumptions about your background or knowledge of Linux. You need no prior knowledge to benefit from this book. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.

$ Check price
24.9924.99Amazon 4.5 logo(101+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Ad