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:
- It adds the newly created user account into /etc/passwd, /etc/shadow, /etc/group and /etc/gshadow files.
- Home directory is populated with the directory for the new user.
- 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:
- Username: Username of the user
- Password: which is stored in /etc/shadow file
- User ID: which is also known as UID
- Group ID :which is also known as GID
- User information: This is an optional field and it is used to define extra information about the user.
- Home Directory: It tells us about the location of the user’s home directory.
- 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