Introduction

This lesson will cover how to switch to other accounts and how to run commands and programs as other users.

The su command

One way to start a session as another user on the system is to use the su command. The syntax for su is:

su [username]

If no arguments are supplied, it assumes that you are trying to become the superuser or root account. Executing su without any options is the same thing as su root.

The su options

Your current environment is passed to the new shell unless you specify a hyphen or dash (-). In that case, su creates an environment like the user logged in directly. Use the -c option to specify a command to be executed. If the command you want to execute is more than one word in length, then you need to surround it with quotes ('command command')

Option Meaning
- username A hyphen is used to provide an environment similar to the user logged in directly.
-c command username Specify a command to be executed.

The whoami command

If you want to know what user you are working as, run the whoami command. If you run this, it should return your current account name.

Examples

Example 1: Run whoami and switch user

Switching user.

$ whoami
robin
$ su nikki
Password: 
$ whoami
nikki
Example 2: Run with - option

Suppose you currently logged in as user robin . Create an variable and switch to nikki, and you can still access this variable.

$ whoami
robin
$ export TEST=1
$ echo $TEST
1
$ su nikki
Password:
$ whoami
nikki
$ echo $TEST
1

However, if you switch to nikki with - option, you will be logged into an new environment. In this new environment, you won't be able to access that variable and you are placed to nikki's home directory.

$ su - nikki
Password: 
$ whoami
nikki
$ echo $TEST
 
$ pwd
/home/nikki 

The sudo - Super User Do

Another way to switch users or execute commands as others is to use the sudo command. The syntax for sudo is:

sudo command

The details of sudo is covered in sudo command.

References & Resources

  • N/A