ubuntu change user

When working in the terminal, you’ll often encounter situations that require you to log in as a different user. The switch user (su) command is used for this.

Sometimes, users only want to change the username and hostname rather than switch to a different user.

This sounds simple, but in reality, changing the username is a big deal as it affects config files. Programs that use the old home directory path in their configs might stop working, or you might lose their settings.

As such, we’ll explain the proper steps required for both of these scenarios in this article.

Switch User In Terminal

As stated, you can use the su command to switch to a different user during a login session. For instance, we’ll switch to the user anup.

su anup

If you don’t specify any username, the command is supposed to switch to the root shell. But on Ubuntu, normal users don’t have access to the root account for security reasons. Thus, you’ll need to use sudo for the command to work.

sudo su

You can press CTRL + D or type exit to leave the root shell. This’ll get you to the shell of the previous user. You can also switch to a different user directly by using su as done earlier.

su anup

Finally, you should know about the -, -l, or --login options. These will start the shell as if you directly logged in as the user. This means environment variables like PATH are initialized, and you’ll land at the user’s home directory instead of the current directory.  

su - anup

Change User Details

Ubuntu’s shell prompt follows a username@hostname format by default.

anup@linuxstart:~$

If you want to change the hostname, you can use hostnamectl. We’ll change the hostname from linuxstart to mypc as an example.

hostnamectl set-hostname mypc

If you want to change the username, you can use usermod. Make sure the user you’re trying to change isn’t correctly logged in and run

sudo usermod -l newUsername oldUsername

As mentioned earlier, changing the username can have some unwanted implications. Programs may stop working due to incorrect values in config files. It’s not really practical to manually edit every config file on the system. A better solution would be to move the user’s home directory.

For instance, let’s say we renamed a user from jacques to anup. The user’s home path is currently /home/jacques. The following command will move the home directory to /home/anup.  

sudo usermod -d /home/anup -m anup
Anup Thapa

Senior Writer

Anup Thapa is a Linux enthusiast with an extensive background in computer hardware and networking. His goal is to effectively communicate technical concepts in a simplified form understandable by new Linux users. To this end, he mainly writes beginner-friendly tutorials and troubleshooting guides. Outside of work, he enjoys reading up on a range of topics, traveling, working out, and MOBAs.