Any number of user accounts can be made a part of a group in FreeBSD. Every group has a unique name and GID that identifies it. There is a UserID or UID for every process, and it is used along with the GroupID or GID to assess what is it allowed to change.
Adding a user to a FreeBSD group with the pw command
To add users to a group, we will be using the pw command-line utility. The intended purpose of this command is to provide the root user with a straightforward and intuitive interface to create and customize user groups.
So you’d need root access to follow the instructions in this guide. Use the sudo command as illustrated below:
Replacing a user’s group membership
The instructions in this section will remove the previously held memberships of the group. To see what groups a certain user ‘younis’ is a part of, use the id command:
Let’s add this user to a group named teamtwo. Enter the pw command as under:
To add this user younis to two groups with just one line of command, use the combination below
Where wwwusers is the second group, we want to add user younis to. The –G switch used in the command above specifies the first group as primary and the following groups as secondary.
Adding FreeBSD users to a new group without replacing pre-existing memberships
The command syntax presented below can add users to a new group without removing their existing group memberships.
$ pw group mod {groupNameHere} -m {userNameHere1,userNameHere2,...}
Let’s demonstrate with an example. Check the user groups with the id command:
Then to add this user to the teamtwo group, use the command syntax as we’ve used below:
You can make sure that the previous group memberships are retained by running the id command on that user.
Adding a new user to a group in FreeBSD
This section will focus on creating a new user and adding it to a pre-existing group. You can use the pw command again to both create the user and add it to a group.
With the commands above, we’ve created a new user named younis2, added him to the secondary testing group, and set a password for the user account.
To run a verification on the user account, use the id command again:
Check the members in a FreeBSD group
The pw command can also be used to display the names of all the users in a certain group. To check the members in our testing group, we’d issue the command below:
Alternatively, we can use the grep command on /etc/groupfile.
To list the groups a certain user is a part of, run the following group command:
You can use the id command to see the same result:
$ id -G -n younis2
Conclusion
This tutorial was all about adding users to groups in FreeBSD. We learned how to replace memberships for user accounts and how to add users to new groups without replacing their memberships. You’ve also learned how to create and add new users to pre-existing groups on the go.