Home » Tech Tips » Switch User “su” Command in Linux with Useful Examples

Switch User “su” Command in Linux with Useful Examples

The su command is also known as switch user. This command is used to become another user during a login session. When invoked without a username, su defaults switch to the superuser. Basically, the su command is used to change the currently logged-in user to another user without logging out from the system.

It is a frequently used command mostly by Linux terminal users. This tutorial will help you understand the uses of the Linux su command with examples.

Syntax:

su [OPTIONS] [USER] [OPTIONAL ARGS...]

su Command Examples in Linux

Let’s begin with a basic example. I’m Logged in to my system with user ‘root’, verified the identity using whoami command.

whoami

Output:

mytechmint

Then switch to root user with su command. Again verified the identity.

su - root
whoami

Output:

root

Things to Know:

  • Invoke the su command without username becomes the superuser (root).
  • Using hyphen (-) with switching invoke login shell scripts. This is used to provide an environment similar to what the user got at direct login
  • The current environment is passed to the new shell with effective environment variables to switch users.
Related:  How to Search Files with Case-Insensitive Names in Linux

The sudo privileged users can also prefix sudo with su command. like:

sudo su - root 

Sometimes, you may only need to switch user to run a single or few commands only. In that condition, su provides you -c the option to run the command as another user without actually switching the shell.

su - root -c "whoami"

Output:

root

“su” Command Line Options

Linux su command has only a few but very useful options. These options are very useful while automating tasks with shell scripts.

    1. -c, --command Use this option to pass command to the invoked shell. With the help of this, you can run the command as another user.
    2. -, -l, --login make the new shell a login shell. So all the environments will be set as similar to users logged-in directly.
    3. -s, --shell Change the default SHELL that is specified in “/etc/passwd” file.
    4. -m, -p, --preserve-environment Use this option to preserve environment variables, This is helpful while running the command temporarily as another user.
Related:  Custom Commands for Linux Terminal

For “su” command help page use the below command.

su --help

For “su” command manual page use the below command.

man su

Leave a Comment