Group management and user account management is one of the regular tasks performed by a Linux sysadmin. Adding to and removing from groups is part of these tasks.
Suppose you are in a situation where you need to remove a user from a group. Take a practical example where you don’t want to give a user access to run docker containers. One way would be to remove this user from the docker group.
How to remove user from group
Now how do you remove a user from a group? There are two steps involved here:
- Find the groups of the user
- Add the user to all of its existing group except the ones you want to remove it from
Step 1: Find the groups of the user
id -nG user_name
This will list all the groups of the user.
abhishek@nuc:~$ id -nG prakash prakash adm cdrom sudo dip plugdev lpadmin sambashare docker
Step 2: Removing user from the group
You can use the usermod command here with option G. With option -G, you specify which groups this user will belong to. If the user is currently a member of a group which is not listed, the user will be removed from the group.
sudo usermod -G group1,group2,group3 user_name
Do note that the group names must be separated by comma but there should be no whitespace between them.
sudo usermod -G prakash,adm,cdrom,sudo,dip,plugdev,lpadmin,sambashare prakash
Now if I display the groups, you can see that it is no longer a member of docker group.
abhishek@nuc:~$ id -nG prakash prakash adm cdrom sudo dip plugdev lpadmin sambashare
I hope you like this quick little Linux tip on removing user from groups. Questions and suggestions are always welcome.