How to Add a User to a Group in Linux

This article is about adding a user to a group but now the question is why a user joins a group and how we can do it. This can be associating a user to a new group or may be changing its group.

The root user can create a group and can add a user to an existing group with the commands described in the remaining section.

There are two types of group: primary group and the secondary group. A user is associated with only one primary group and zero more secondary groups. The groups are contained in file /etc/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 the 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.

root@Inspiron-1440:~# id raghu
uid=1000(raghu) gid=1000(raghu) groups=1000(raghu),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),109(lpadmin),124(sambashare)

Thanks for reading the article and let me know your thoughts.

Read Also:

Raghu 12:20 am

Comments

Your email address will not be published. Required fields are marked *

All comments are subject to moderation.