0
0
Linux-cliHow-ToBeginner · 3 min read

How to Switch User in Linux: Simple Commands Explained

To switch user in Linux, use the su command followed by the username, or use sudo -i -u username for switching with elevated privileges. These commands let you operate as another user without logging out.
📐

Syntax

The basic syntax to switch user in Linux is:

  • su [username] - Switches to the specified user account.
  • sudo -i -u [username] - Switches to the specified user with root privileges if allowed.

If no username is given, su switches to the root user by default.

bash
su [username]
sudo -i -u [username]
💻

Example

This example shows switching from the current user to user alice using su and then back to the original user.

bash
su alice
whoami
exit
whoami
Output
alice originaluser
⚠️

Common Pitfalls

Common mistakes when switching users include:

  • Not having the target user's password when using su.
  • Trying su without root privileges or sudo rights.
  • Confusing su and sudo usage.

Remember, su requires the target user's password, while sudo uses your own password if you have permission.

bash
Wrong:
su alice
# Fails if you don't know alice's password

Right:
sudo -i -u alice
# Uses your password if you have sudo rights
📊

Quick Reference

CommandDescription
suSwitch to root user or specified user with their password
su - usernameSwitch to specified user with login environment
sudo -i -u usernameSwitch to specified user using sudo privileges
exitReturn to previous user session

Key Takeaways

Use su username to switch user by entering their password.
Use sudo -i -u username to switch user with your sudo rights.
su switches user environment; sudo runs commands with elevated rights.
Always use exit to return to your original user session.
Not knowing the target user's password will block su but not sudo if permitted.