The main idea of this post comes from here: How To Create a New Sudo-enabled User on Ubuntu 20.04 [Quickstart]. You can go there for other versions and distributions.
First, we should add a new user to our system
adduser, with basic configurations. You should replace “tony” with your username.
# adduser tony
It will immediately prompt you to set password for this user.
Following is some extra information, which may not make sense. So just press Enter to leave them by default.
Now that we have the new user, add it to
sudo group using
# usermod -aG sudo tony
This is it, then you should be able to use
sudo as tony.
Change to the user using
su tony or login to the user using
login tony, and try to run a command with
sudo. For example,
sudo apt update. If it prompts you to enter the password, then everything works well.
However, there is possibility that you may encounter this:
-bash: sudo: command not found
It may happen when you’re in a docker image, which do not have
sudo command by default. So you should install it as root.
# apt install sudo
After installation, the problem will be no more.
Now that we have the user, how can we login as the new user, instead of root by default?
For SSH connection, we can simply change the username and password for the server IP. If you are using docker, things would be a little more tricky. For example, if you have a container called “tony-container”, in which you added a user called “tony”, then you can use this command below to run the bash in it with this profile in its home directory.
docker exec -it --user tony -w /home/tony tony-container bash
If you care about highlighting, here is a example
.bashrc file. Copy it, or override options respectively in yours. One thing to notice is that, in a docker container,
TERM variable may not be set. You can either set it in
docker exec using
-e TERM=xterm-256color or add
export TERM=xterm-256color in
# ~/.bashrc: executed by bash(1) for non-login shells.