How to add a user to group in Linux

This post will help you to understand how you can add a user to a group in Linux. Though it is a very simple task, if you have any confusion regarding it, this guide will clear all your doubts.
There are two ways of adding a user to a group. You can use the useradd or usermod commands for doing this task.
  • useradd: It is used to create a new user as well as it can be used to update the default new user information.
  • usermod: It is used to modify a user account. This can be used to add a user to existing group.
Talking about groups, there are two types of groups in Linux
  1. Primary Group: It is the group applied when user login using any method(ssh, tty, GUI) etc. Typically it is same as the login name.
  2. Secondary Group: These are the supplementary groups which the user is also a member of.
Now, let us see the commands used to add a user to a Group.

Add a new User Account to a Group

Below example will create a new user john with sales group as his primary group and mktghrd as his secondary group. Ensure that primary and secondary groups exist in the system before running this command
# useradd -g sales -G mktg, hrd john
To add a new user Kumar with primary group Engineering
# useradd -g Engineering Kumar

Add an existing User Account to a Group

If you already have a user and you want to add the same to an existing group on your Linux machine, we will use usermod command.

Assign Secondary Group to an existing user

Let us suppose if you have an existing user david and you want to add the same to a secondary group webmasters, you can use below command.
# usermod -a -G webmasters david
You can check and verify the same by id command, as explained in the example above, user david has been added to secondary group webmasters.

Assign Primary Group to an existing user

Also, each user has primary group assigned to it like user david has primary group david. If you want to change the primary group of user david as web-admin, then run below command. For changing primary group (-g) option will be used with usermod command.
#  usermod -g web-admin david

To list all the users belonging to a particular group, we can use lid command.
linuxforgeek:~# lid -g webmasters
 david(uid=3028)
 john(uid=3029)
 kumar(uid=3030)
 jack(uid=3031)
To list all the groups of a particular user use groups command.
linuxforgeek:~# groups david
david : web-admin webmasters sudo