How to Become Root or Any Other User Using the Linux Command Line

The subsitute-user command allows easy access to other user accounts

The sudo command allows you to run any command as another user and is commonly used to elevate permissions so that the command is run as an administrator (which in Linux terms is known as the root user).

However, to run as another user for a prolonged period of time then use the su command.

Technically, su stands for substitute user.

Switch to the Root User

The way you switch to the root user differs by distribution. For example, on Ubuntu-based distributions such as Linux Mint, Ubuntu, Kubuntu, Xubuntu, and Lubuntu, switch using the sudo command as follows:

sudo su

If you are using a distribution which allowed you to set a root password when you installed the distribution then you can simply use the following:

su

If you ran the command with sudo then you will be asked for the sudo password but if you ran the command just as su then you will need to enter the root password.

whoami command

To confirm that you have indeed switched to the root user type the following command:

whoami

The whoami command tells you which user you are currently running as.

Switch to Other Users and Adopt Their Environment

The su command switch to any other user's account. This ability is useful when you're testing user-account provisioning.

For example, assume you created a new user called ted using the useradd command. Switch to the ted account using the following command:

su ted

As it stands, the above command would log you in as ted but you wouldn't be placed in the home folder for test and any settings that ted has added to the .bashrc file will not be loaded.

You can, however, log in as ted and adopt the environment using the following command:

su - ted

This time when you log in as ted, you will be placed into the home directory for ted.

Execute a Command After Switching User Accounts

To switch to another user's account but have a command run as soon as you switch, use the -c switch as follows:

su -c screenfetch - ted

In the above command, the su switches user, the -c screenfetch runs the screenfetch utility and the - ted switches to the ted account.