How to Add User to Group in Linux

This post will guide you how to add new and existing users to primary or secondary groups in your Linux Operating systems. How do add a user to a group in Linux. How to remove a user from a group. How to create or delete a Group.

add user to group linux 1

Adding a User to a Group


If you want to add an existing user to a secondary group, and you can use the usermod command with -G option.
For Example, if you want to add a user called mytest to another group(mydev), just type:

$ sudo usermod -a -G mydev mytest

You can verify if the secondary group of this user is added, type:

$ id mytest

Outputs:

devops@devops:~$ id mytest
uid=1001(mytest) gid=1001(mytest) groups=1001(mytest),1002(mydev)

Adding a User to Multiple Groups


If you want to add an existing user to multiple secondary groups in your Linux, and you can use usermod command with -G option and names of group separated by common character.

For example, you want to add user mytest to multiple groups(mytest2,mytest3), type:

$ sudo usermod -a -G mytest2,mytest3 mytest

Let’s check if user “mytest” is added to multiple groups by using the following command:

$ id mytest

Outputs:

devops@devops:~$ id mytest
uid=1001(mytest) gid=1001(mytest) groups=1001(mytest),1002(mydev),1003(mytest2),1004(mytest3)

Removing a User from a Group


If you want to remove a user from a group, and you can use the gpasswd command. For example, you want to remove a user called mytest from a group called mytest3. Type:

$ sudo gpasswd -d mytest mytest3

Outputs:

devops@devops:~$ sudo gpasswd -d mytest mytest3
Removing user mytest from group mytest3

devops@devops:~$ id mytest
uid=1001(mytest) gid=1001(mytest) groups=1001(mytest),1002(mydev),1003(mytest2)

Creating a Group


If you want to create a new group in your current Linux system, and you can use the groupadd command with a group name(mytest4), type:

$ sudo groupadd mytest4

Deleting a Group


If you want to delete an existing group, and you can use the groupdel command with a group name, type:

$ sudo groupdel mytest4

Changing the Primary Group of a User


If you want to change a user primary group, and you can use the usermod command with -g option.

For example, you want to change the primary group from mytest to mytest4. Just issuing the following command:

$ sudo usermod -g mytest4 mytest

Outputs:

devops@devops:~$ sudo usermod -g mytest4 mytest
devops@devops:~$ id mytest
uid=1001(mytest) gid=1005(mytest4) groups=1005(mytest4),1002(mydev),1003(mytest2)
devops@devops:~$

If you want to get more information about both useradd and usermod commands, and you can type the following man command at the shell prompt:

$ man usermod
$ man useradd
$ man groupadd

Conclusion


You should know that how to add a user to a secondary group or multiple groups in your CentOS or RHEL or Ubuntu Linux.

You might also like:

Sidebar



back to top