Psychz - Nikhil
Votes: 0Posted On: May 29, 2017 05:22:11
You can add any user to group with the help of multiple methods. You can add the user to the group while creating the user itself or add existing user to a group. You can also add a user to multiple groups. Here are some of the methods and useful commands by which a user can be added to a group.
Prerequisites
CentOS operating system - We are using CentOS 7 in this case.
Adding the Group while creating the user.
Any group can be added to the user while the user is being created. The general syntax for the same is "useradd -G group username". In this case, we will be creating a user "test" and adding it to the group "linux" simultaneously.
useradd -G linux test
(Note: The "-G" option is used to add the group as a secondary group. If you want to add the group as primary please use the "-g" option.)
Adding an existing User to the Group
An existing user can also be added to a group by using the "usermod" command. The general syntax for adding the user to a group is displayed below.
usermod -aG group username
For instance, we are adding the user "test1" to the group "linux". A sample is displayed below for your reference.
usermod -aG linux test1
(Note: "-a" option is used to add the user to supplementary groups. It should always be used with the "-G" option)
Adding multiple groups to a single user
Multiple groups can also be added to a single user using the "usermod" command. The following syntax is used for the following.
usermod -a -G group1,group2,group3 username
There are some useful commands that will help you in listing the groups, finding out which groups are assigned to the user among others. Some of them are listed below.
1. "getent group" - This command is used to list all the groups in the operating system.
2. "groups" - This command is used to view all the groups the username is assigned to. (Syntax : "groups username")
3. "id" - You can also view the numerical IDs associated with each group by running the id command and specifying a username. (Syntax : "id username")
These were some of the commands that are helpful in adding a user to a group in CentOS operating system. We recommend you to go through the man page of these commands for a detailed understanding of all its variants.