useradd command in linux is used to add a new user in the system. In other words, it creates a new login account for a different user. But, only the root user can user useradd command in linux.
useradd [options] [LOGIN]
Explanation: useradd command creates a new user with the name David. To verify the creation of the new user, check the contents of the passwd file, which is in the /etc directory.
The last line shows the entry for the user David. This file contains the list of all the users in the system. Each user entry has seven fields to it.
Name: the name of the user (e.g. David)
Password: marked with x. Not visible
UID: the user ID
GID: the ID of the group to which the user belongs
GECOS: Full user name
User Home Directory: the home directory of the user to manage his files
Default Shell: the shell used by the user for interaction
useradd command by default assigns UID, GID, Home directory and default shell to a new user.
Note: If you create a user, as shown above, you are required to set a password using the passwd command before you login. If you don’t do it and try to login, the system prompts for a password as shown below.
useradd command in linux can be used with various options. Some of the most common ones are:
-c : option assigns the value of GECOS field. For example:
Here the new user Steve is assigned the GECOS value as Steve Smith which is the full name of the user.
-d : option creates a home directory with a name and path of your choice. By default the home directory is created in /home directory with the same name as the user’s name. But with –d option you can create a home directory of your choice. For example:
-u : option assigns a user ID of your choice. For example:
Thus, the user David is given the UID 5555.
-g : option assigns the user to an existing group rather than creating a new group for it. For example:
Thus, the user David is assigned to the group with GID 1007 which is an existing group. Steve is already a member of 1007.
-G : option adds the user to supplementary groups i.e. other groups to which a user might belong. For example, let’s consider that David’s primary group is Mac and now he joins two other projects – Linux and Windows. Now, the supplementary groups for David are – Linux and Windows.
Mac is the primary group specified by “-g” while Windows and Linux are the supplementary groups specified by the “-G” option. The lid command shows that the user David belongs to three groups. A look at the /etc/group file shows that Linux and Windows are the supplementary groups for David.