Linux Command To Add User To A Group

Add a New Group

First we take a look into how we can add a new group to the system. A new group can be created with the groupadd command.
$ groupadd groupname

Add an Existing User to a Group (Secondary group)

To add an existing user to an existing group, usermod command will work in following way.
$ usermod –a -G groupname username
$ usermod –a -G mygroup shyna
The above command adds the user ‘shyna’ to the group ‘mygroup’.

Change a User’s Primary Group

Root user can change the group of user. A user’s primary group can be changed with -g option.
$ usermod -g groupname username
This group must exist on the system.

Add a User to Multiple Groups

A user can also be added to a number of groups with the same command as single group.Here series of groupnames separated by commas will be placed in place of groupname as below command.
$ usermod –a -G groupname1,groupname2,groupname3 username
There can be any number of groups as here three groups are present named groupname1,groupname2 and groupname3.

Add primary Group to new user

Here we are creating a new user and assign a primary group to him in just one command.
$ useradd -g groupname username
This is the command which creates a user and assigns a group to him. Here the group to which user has been assigned is primary group

Add secondary Group to new user

Here we are creating a new user and assign a secondary group to him in just one command.
$ useradd -G groupname username
So as we have realized here ‘g’ is used for assigning primary group and ‘G’ is used for assigning secondary group.

View a List of All Groups

A user’s groups can be listed with ‘groups’ command.
root@Inspiron-1440:~# groups
root
If a username is provided to this command, then that user’s groups will be listed.
root@Inspiron-1440:~# groups raghu
raghu : raghu adm cdrom sudo dip plugdev lpadmin sambashare
id command also tells a user’s primary and secondary groups.