0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use su Command in Linux: Syntax and Examples

The su command in Linux lets you switch to another user account or become the root user by entering their password. Use su alone to switch to root or su username to switch to a specific user.
📐

Syntax

The basic syntax of the su command is:

  • su: Switch to the root user by default.
  • su username: Switch to the specified user.
  • su - username: Switch to the specified user and load their login environment.

Here, username is the target user you want to switch to. The dash - means to start a login shell, which loads the user's environment variables and settings.

bash
su [options] [username]
💻

Example

This example shows how to switch to the root user and then to another user named alice. It demonstrates entering the password and changing the shell prompt.

bash
su
# Enter root password when prompted
whoami
su - alice
# Enter alice's password when prompted
whoami
Output
root alice
⚠️

Common Pitfalls

Common mistakes when using su include:

  • Not entering the correct password causes failure to switch users.
  • Forgetting the dash - means the new user's environment is not loaded, which can cause unexpected behavior.
  • Trying to use su without proper permissions or sudo rights.

Always ensure you have the right password and use su - username to get the full user environment.

bash
su alice
# May not load alice's environment fully

su - alice
# Loads alice's full login environment
📊

Quick Reference

CommandDescription
suSwitch to root user
su usernameSwitch to specified user without loading environment
su - usernameSwitch to specified user with full login environment
exitReturn to previous user shell

Key Takeaways

Use su to switch users by entering their password.
Add a dash - to load the target user's full environment.
Incorrect passwords prevent switching users.
Use exit to return to your original user.
su requires knowing the target user's password.