This article demonstrates how to create or remove a user on Linux.
On Windows it’s possible to add a new user through the GUI. But in Linux it’s more common to do this via the terminal. In this article I will do a short demonstration creating a new user. I will also add it to the sudoers group so that it can run sudo commands. Finally I will remove the user.
Creating a user
You can create a new user with the command: sudo useradd -m [username]. The -m option also creates a user folder for the user.
Now as you can see below a new directory was created for user2.
Then we need to create a password for the new user with sudo passwd [username]
If we want the new user to be able to run commands as root, we need to add the user to the sudoers group: sudo usermod –aG sudo [username]
Note: It could be that the new user doesn’t use the regular bash shell yet and only a $ shows up in his terminal. To change this type ‘sudo chsh -s /bin/bash [username]’. Now the user will use /bin/bash.
We can look at the /etc/passwd file and search for the word ‘user2’ with the following command: ‘cat /etc/passwd | grep user2’. In the output we can see that user2 was created and has his own home directory.
We can switch to the new user with ‘su [username]’. After entering the password we log in as the new user.
Change username & home folder name
If you want to change the name of a user or user directory, you need to login as a different user or as root first.
To change the username: ‘sudo usermod -l [new username] [old username]’.
Note: You may get a message that the user is still using a process, which makes it impossible to rename it. This mainly happens on Ubuntu. If you make sure that you are logged in as a different user and use the same command in a new terminal this issue should go away.
Now when we look at /etc/passwd we see the username changed to ‘new_name’ but the user directory is still ‘user2’.
We can rename the user directory with ‘sudo usermod -d /home/[new name] -m [username]’.
Now the name of the user directory changed as well:
Removing a user
To remove a user you need to log in as root or a different user that can run sudo commands.
Then run: ‘sudo userdel [username]’. If you also want to remove the directory use: ‘sudo userdel -r [username]’.
If the user still has processes running you can stop them with ‘sudo killall -u [username]’ and then remove the user, or use ‘userdel -f [username]’ to force it even if processes are still active.
This was how to create or remove a user on Linux. I hope it was useful!