Add Linux User to Group


#1

You can add an user to a group while creating it or you can set a group for an existing user. You need root privileges to add a user to a group.

1. Set group for new user

You can use useradd command to create user. useradd command creates a new user on the system using specified values and default values. To set a group for new user, you can use -G parameter of useradd command.

$ useradd -G {groupname} username

After you run that command, you can check new user using id command. You will see all groups which user belongs to.

$ useradd -G administrators johndoe
$ id
uid=1001(johndoe) gid=1001(johndoe) groups=1001(joendoe),1000(administrators)

As a defacto rule, each user in Linux systems have its own user group with same name as loginname as default to keep user files safe. So no one can access the files which user created until s/he give permission to another group. This group is named as primary group. If you want to use another group as primary group for user, you can use -g parameter of useradd command.

$ useradd -g administrators johndoe
$ id
uid=1001(johndoe) gid=1000(administrators) groups=1000(administrators)

2. Add an existing user to a group

If you want to add an existing user to a group you have to use usermod command. usermod is a command which helps you to change user details like home folder, primary/secondary groups, user lock status, user expiry date etc.

To add a new group to secondary groups of an user, you can use -G parameter of usermod command. If you want to keep all current secondary groups of user, you should also use -a (append) parameter. Otherwise usermod will remove all other secondary groups assignments.

$ usermod -G {groupname} username
$ usermod -aG {groupname} username
# without -a parameter 
$ usermod -G web johndoe 
$ id johndoe
uid=1001(johndoe) gid=1000(administrators) groups=1002(web) 

# with -a parameter 
$ usermod -aG web johndoe
$ id johndoe
uid=1001(johndoe) gid=1000(administrators) groups=1000(administrators),1002(web)

You can also change primary group of user using -g parameter of usermod command.

$ usermod -g web johndoe
$ id johndoe
uid=1001(johndoe) gid=1002(web) groups=1000(administrators)