Managing Groups in Linux

Groups play an important role in controlling the access to files and resources in Linux. However, group management is a little different in Linux from that of Windows. One difference is that when a user is created, a group with the same name as the user is also created. So if we set up a user ffugazi a group called ffugazi is also created and the user object is put in it. Another difference is the idea of nested groups does not exist in Linux, a single group will be applied to a single file.

Users can have primary and secondary groups. Primary groups are created when a user account is created and have the same name as the user; when a user carries out an action, by default it uses this group’s context for all actions. For example, when a user creates a file the group with the same name as their account (the primary group) is applied to the file. Primary groups are detailed in the /etc/passwd file.

Secondary groups are those a user may be added to once they already have an account, can be called anything, and can be used to grant access to shared resorces. They are detailed in /etc/group file.

This arrangement of primary and multiple secondary groups that a user can be a member of does mean that you have to remember that when you create a file unless you apply a shared group, no one else will have access by default, the chgrp command will need to be used to apply group to a file.

So how do we create a group in Linux?

>sudo groupadd testgroup

Removing a group is equally easy.

>sudo groupdel testgroup

If we want to modify a group there is the handy groupmod command. For example if we want to change the name of the group to testgrp:

>sudo groupmod -n testgrp testgroup

Adding or removing a user to or from a group is done using the gpasswd command. Adding users to groups can also be done using the adduser, useradd and usermod commands too.

Adding users to groups
>sudo gpasswd -a ffugazi testgrp
OR
>sudo adduser ffugazi testgrp
OR
>sudo useradd -G testgrp ffugazi
OR
>sudo usermod -a -G testgrp ffugazi

usermod is also useful for adding a user to multiple groups
>sudo usermod –a –G group1,group2,group3 ffugazi

Removing a user from a group
>sudo gpasswd -d ffugazi testgrp
OR
>sudo deluser ffugazi testgrp

Users can also be made an admin for the group.

>sudo gpasswd -A ffugazi testgrp

If we wanted to make a user an administrator on our Linux system we would use the command below to grant sudo access:

Ubuntu / Debian
>sudo usermod -a -G sudo ffugazi
On RHEL / Centos
>sudo usermod -a -G wheel ffugazi

If a user needs access to resources only accessible to their secondary group they would use:

>newgroup testgrp

Resources the group testgrp have permissions to access would now be available.

Verifying information about users and groups can be done with the getent and groups commands