Custom Search

How to add user to a group in Linux operating system

We can assign user to a group during adding a new user account. But how do we add existing user to a group? This tutorial is a guide on how to add user to a new group. The right Linux command for the job is the usermod command.

This is some information about Linux usermod command from manual page:

NAME
usermod - modify a user account

SYNOPSIS
usermod [options] LOGIN

DESCRIPTION
The usermod command modifies the system account files to reflect the
changes that are specified on the command line.


As you can see, the Linux usermod command can be used to modify a user account. However in this tutorial, we'll only use usermod command to add user to a new group. For this example, we'll create a new group to practice. Use the groupadd command to create a new group:

luzar@ubuntu:~$ groupadd programmer
groupadd: unable to lock group file
luzar@ubuntu:~$ sudo groupadd programmer
[sudo] password for luzar:
luzar@ubuntu:~$

Don't forget to use sudo command in Ubuntu, else you'll get the groupadd: unable to lock group file error as in the example above. Check whether the programmer group has been created in /etc/group file:

luzar@ubuntu:~$ less /etc/group | grep programmer
programmer:x:1001:
luzar@ubuntu:~$

Next, we are going to add user to a new group. For this example, we are going to add a user called luzar to the programmer group. Below are step by step instructions.

Use usermod -G option to add user to a new group:

luzar@ubuntu:~# sudo usermod -G programmer luzar

Use Linux groups command to check whether the programmer group has been added to luzar's group:

luzar@ubuntu:~# groups luzar
luzar : users programmer
luzar@ubuntu:~#

As you can see, the user luzar now has programmer as a second group. We can also check /etc/group to verify user currently in the programmer group:

luzar@ubuntu:~$ less /etc/group | grep programmer
programmer:x:1001:luzar
luzar@ubuntu:~$

That's all.

2 comments:

  1. It would be wise of you to include the -a option when using usermod to add a user to a group.

    Please see: http://askubuntu.com/q/54363/1859

    ReplyDelete
  2. exactly, what aendruk said I can concur! I had to manually reenstate the groups my user belonged to before. so i recommend to change the line to :

    sudo usermod -a -G programmer luzar

    ReplyDelete

Please keep comment relevant and strictly no spam will be tolerated. Thank you.