Adding a User in Linux
Adding a user in Linux is a common administrative task. The useradd command is used to create a new user account. Here’s a step-by-step guide on how to use it, along with explanations of various flags and related files.Basic Command
To add a new user, you can use the following command:
Code:
sudo useradd username
Common Flags
- Comment (-c): This flag allows you to add a comment or description for the user. For example:
Code:sudo useradd -c "John Doe" johndoe
- Shell (-s): This flag specifies the user's login shell. For example, to set the shell to /bin/bash:
Code:sudo useradd -s /bin/bash johndoe
- Home Directory (-d): This flag sets the user's home directory. By default, the home directory is created under /home/username. To specify a different directory:
Code:sudo useradd -d /custom/home/directory johndoe
- Create Home Directory (-m): This flag ensures that the home directory is created if it does not exist:
Code:sudo useradd -m johndoe
Using /etc/skel
The /etc/skel directory contains default files and directories that are copied to a new user's home directory when the account is created. This can include configuration files, directories, and other initial setup files.For example, if /etc/skel contains a .bashrc file, this file will be copied to the new user's home directory when the account is created.
Setting or Changing the Password
To set or change the password for a user, you can use the passwd command:
Code:
sudo passwd johndoe
Understanding UID and GID
- UID (User ID): This is a unique identifier assigned to each user on the system. It is used by the system to identify the user and manage permissions. UIDs are typically assigned sequentially starting from a predefined number (e.g., 1000 for regular users).
- GID (Group ID): This is a unique identifier assigned to each group on the system. It is used to manage group permissions. Each user is assigned a primary GID, which corresponds to their primary group.
Understanding /etc/passwd and /etc/shadow
- /etc/passwd: This file contains user account information. Each line represents a user and includes fields such as username, user ID (UID), group ID (GID), home directory, and login shell. Passwords are not stored here for security reasons.
- /etc/shadow: This file contains encrypted password information and additional account security details. Only root and privileged users can read this file. Each line corresponds to a user and includes fields such as the username, encrypted password, and password expiration information.
Sample useradd Command with All Flags
Here’s an example of a useradd command using all the flags on the same line:
Code:
sudo useradd -c "John Doe" -s /bin/bash -d /custom/home/directory -m johndoe