Linux based OSs use groups to organise and administer users on a machine. The main objective is to define a set of privileges such as reading, writing or executing permissions for a given set of users.
There are two types of groups in Linux.
- Primary group: This is configured when a new user account is set up and recorded in the ?etc?passwd file. This group is assigned to all files a particular user creates.
- Secondary group: These groups show up in the ?etc/group file and specifies one or more groups to which a user belongs.
Note that only the root user or users with sudo access can assign or modify group settings.
Adding an existing user to a group
Existing users can be added to one or more secondary groups using the usermod -a -G command. Here’s how.
sudo usermod -a -G groupname username
You can also mention as many groups as you want after the -G flag separated by commas. Make sure to add the append (-a) flag as well otherwise the user will be removed from all other groups not mentioned after the -G flag.
For example, if you want to add a user dexter to groups lab and house this is the command you’ll use.
sudo usermod -a -G lab, house dexter
Note that the usermod command doesn’t show any output on successful execution. However, you will see an error if the specified group(s) or the user doesn’t exist.
To see what groups a user is a member of, use the id command followed by the username.
To see only secondary groups, use the group command followed by the username.
Removing a user from a group
Users can be removed for groups using the gpasswd command. Here’s how.
sudo gpasswd -d username groupname
Also read: How to run Cron Jobs every five minutes?
Creating/Deleting a group
Creating and deleting groups is rather easy as well. You’re going to have to use the groupadd and groupdel commands respectively.
sudo groupadd NewGroup
Or if you want to delete a group,
sudo groupdel NewGroup
Changing a user’s primary group
Changing a user’s primary group involves using the usermod command with the -g flag.
sudo usermod -g groupname username
Creating a new user and assigning groups in one command
Lastly, here’s how you can create a new user and assign primary and secondary groups to them in one command.
sudo useradd -g <Primary Group> -G <Secondary Group(s)> <Username>
Also read: RM command in Linux explained with examples