How to add or delete a user in Linux | Ubuntu Server

How to add a user to Linux | Ubuntu Server

One of the basic commands to add a user to a linux server is ‘useradd’. Today, we will learn how to use this command with some properties.

When we run ‘useradd‘ command in Linux terminal, following major actions are performed in the server:

  1. It adds the newly created user account into /etc/passwd, /etc/shadow, /etc/group and /etc/gshadow files.
  2. Home directory is populated with the directory for the new user.
  3. Automatically assigns ownership and default permissions to the home directory for the user.

Basic syntax for the useradd command is:

useradd [options] username

For Example

# useradd amittal
Adding password for user amittal.
New new UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.

Once the new user is created, its entry is automatically created in /etc/passwd file. You can verify this information by running the following command:

# cat /etc/passwd

It will display all the users on the server. For example:

amittal:x:111:111:amittal:/home/amittal:/bin/bash

The above mentioned entry has a set of seven colon-separated fields. These fields are as follows:

  1. Username: Username of the user
  2. Password: which is stored in /etc/shadow file
  3. User ID: which is also known as UID
  4. Group ID :which is also known as GID
  5. User information: This is an optional field and it is used to define extra information about the user.
  6. Home Directory: It tells us about the location of the user’s home directory.
  7. Shell: Location of the user’s shell: /bin/bash.

How to delete a user from Linux | Ubuntu Server

Removing the user from the server removes the ssh access as well as user’s file and ownership to the home directory. In order to remove user, you can use userdel command.

Most probably you will need root access to delete a user from the Linux server. You can run following commands:

# sudo su
# Provide sudo Password:
# userdel amittal

Optional, we can also use the following command:

# userdel -r amittal

This command deletes user’s home directory and mail spool.

Note:
Please make sure that you use the above mentioned option ‘-r’, if you are certain that you no longer need their files or mail because it will delete user’s home directory.

Change the Default Home Directory Of the user

You can use usermod command to change the default home directory of a user:

# sudo usermod -d /directory/path username

for example:
# sudo usermod -d /mnt/newdirectory amittal

Confirm the change by checking the user in /etc/passwd file:

# grep amittal /etc/passwd

Old information:
amittal:x:1035:1035::/home/amittal:/bin/bash

New Information:
amittal:x:1035:1035::/mnt/newdirectory:/bin/bash

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.