Q: How do I add a user to a group on my Linux system?
A: You can add an existing user to a group, or add a new user and add them to an existing group. Since you did not specify we will cover both. We will use the id command to see the results of each group change.
Add an Existing User to a Secondary Group
When you create a new user they are automatically added to a group of the same name. So if you created a user named joseph, the system will automatically create a group named joseph and add the user to that group.
[root@centos7 ~]# useradd joseph
[root@centos7 ~]# id joseph
uid=1001(joseph) gid=1001(joseph) groups=1001(joseph)
If you want to add the user to another (or secondary) group, you can use the usermod command. For example if you wanted to add joseph the the wheel group you would use usermod like so:
[root@centos7 ~]# usermod -a -G wheel joseph
[root@centos7 ~]# id joseph
uid=1001(joseph) gid=1001(joseph) groups=1001(joseph),10(wheel)
The usermod command is used for modifying a user account, the -a switch tell the command to append, and the -G switch is telling it you are using the group name.
Adding a New User to a Secondary Group
You can specify a secondary group at the same time as adding a new user. To add a new user we use the useradd command. To tell the system to add the user to a secondary group we use the -G switch.
[root@centos7 ~]# useradd -G wheel joseph
[root@centos7 ~]# id joseph
uid=1001(joseph) gid=1001(joseph) groups=1001(joseph),10(wheel)
You can add a new user or existing user to multiple groups at the same time. This is the same whether you using the usermod command or useradd. For example, let’s say we wants to also add joseph to ftp and sysadmin groups. You can simple add all groups separated by a comma with no spaces like so:
[root@centos7 ~]# useradd -G ftp,sysadmin joseph
[root@centos7 ~]# id joseph
uid=1001(joseph) gid=1001(joseph) groups=1001(joseph),50(ftp),1002(sysadmin)
Change Users Primary Group
So far we have added a user to a secondary group, but you can also change a users primary group. For example if you want to change joseph’s primary group to ftp you can use the -g (NOTICE LOWER CASE G NOW) like so:
[root@centos7 ~]# usermod -g ftp joseph
[root@centos7 ~]# id joseph
uid=1001(joseph) gid=50(ftp) groups=50(ftp),1002(sysadmin)
NOTE: Joseph has had his primary group changed. You can not have two primary groups, so he was removed from the original primary group named joseph.