Linux, from its core, is built to have multiple users.
And separating users into different groups is pretty convenient for managing permissions.
A user can be a member of more than one group. This is why the groups are divided into the following two categories:
Primary group: Also known as the login or default group. If the user creates a file, the primary group takes the group ownership. Usually, the primary group has the same name as the user.
Secondary group: Also known as a supplementary group. It is used to grant specific permissions to users. For example, in Ubuntu, only members of the sudo groups can run commands with sudo.
How do you know which group a user belongs to? Let me show you that.
How to check the groups of a user
Here are various scenarios for listing user groups in Ubuntu.
List groups of the current user
To list the groups of the current user, all you have to do is execute a single command without any additional flags:
Yep, all you have to do is execute the
List groups of the other users
If you want to find out the groups to which the specific user belongs, all you have to do is append the username to the
For your reference, here, I checked the groups where the user
groups root groups sagar
I could have used both users in single command as well.
id -gn user_name
List all the groups in Ubuntu
You just learned how to see which groups a user belongs to. How about listing all the available groups? That can be done too.
/etc/group file contains all the necessary information about the local group.
So you can read the contents of that file and easily list the groups:
Similarly, if you want to find a specific group, you can use the grep command to filter the output:
cat /etc/group | grep sudo
In case you are wondering about the meaning of the output, here's what that means:
sudois the name of the group.
xindicates that shadow passwords are being used and can be found at
27is the group ID.
sagaris the list of the group users. You can have multiple of them.
And if they seem irrelevant, you can use the cut command and print the group names only:
cut -d: -f1 /etc/group
Another option is to use the getent command
How to list groups using the getent command
The getent command is used to get entries from the database, including passwd and group database.
This means it can be used for our purpose too!
To get a list of groups, all you need to do is append
group to the getent command:
List every member of a specific group
If you want a list of every user belonging to a specific group, you can use the getent command in the following syntax:
getent group [group_name]
Let's say I want to list every member of the
sudo group, then I will be using the following command:
getent group sudo
Want to know how you can add a user to a group?
If you want to add a user to an existing group and have no idea how to? We have a dedicated guide to solve this issue:
I hope you will find this guide helpful and if you have any queries, let me know in the comments.