How to add users to groups in Linux ; How to remove users from groups

From security reasons, the users and groups are very important in Unix and Linux systems. Every OS geek should know how to create users and groups, add users to groups or modify user and group account informations.

Watch Free Movies

In this article I will teach you how to add users to groups in Linux.

How to create users with custom primary and secondary groups:

I will create the groups and set them as primary and secondary groups for the new created user:

Creating the groups jim, michael and johnson:

$ sudo groupadd jim
$ sudo groupadd michael
$ sudo groupadd johnson

Verifing if the groups have been created, and finding out their GIDs:

$ tail -3 /etc/group
jim:x:1039:
michael:x:1040:
johnson:x:1041:

Creating the test3 user with jim as primary group and michael and johnson as secondary groups with useradd:
the -g  parameter is for adding the user to the primary group, and -G for the secondary groups. Only one group can be set as primary group.

$ sudo useradd -g jim -G michael,johnson test3
$ id test3
uid=1015(test3) gid=1039(jim) groups=1039(jim),1040(michael),1041(johnson)

The GID displayed in the id commands’s output is the ID of the primary group.

Creating the test4 user with the same primary and secondary groups as test3, by using the GIDs:

$ sudo useradd -g 1039 -G 1040,1041 test4
$ id test4
uid=1016(test4) gid=1039(jim) groups=1039(jim),1040(michael),1041(johnson)

How to add an existing user to primary and secondary groups:

I will create the user test5 and add him in primary and secondary groups, by using the names and the GIDs.

$ sudo usermod -g group3 -G group4,group5 test5
$ sudo -g 3000 -G 4000,5000 test6

Usermod is used for changing the user account information. The usermod command’s parameters are the same as the useradd parameters: -g for primary group and -G for secondary groups.

How to remove users from secondary groups:

The gpasswd command is used for working with groups.

How to remove a user from a group with gpasswd: gpasswd -d username groupname.

$ id test4
uid=1016(test4) gid=1039(jim) groups=1039(jim),1040(michael),1041(johnson)
$ sudo gpasswd -d test4 johnson
Removing user test4 from group johnson
$ id test4
uid=1016(test4) gid=1039(jim) groups=1039(jim),1040(michael)

To remove a user’s primary group, set a new group as primary for that user and after that, remove the user from the old primary group.

Scroll to Top