How to Run a Command as a Different User?

Use the su command (switch user).

Syntax#

To use the su command, enter it into a command line as follows:

$ su [options] [username [arguments]]

If a username is specified, su defaults to the superuser (root). Simply find the user you need and add it to the su command syntax.

Some Examples#

Switch to a different user

To switch the logged-in user in this terminal window, enter the following:

$ su –l [other_user]

You’ll be asked for a password. Enter it, and the login will change to that user.

Run specific command as a different user

To run a specific command as a different user, use the –c option:

$ su –c [command] [other_user]

The system will respond by asking you for the user password.

Use a different shell

To use a different shell, or operating environment, enter the following:

$ su –s /usr/bin/zsh

This command opens a root user account in Z shell.

Use a Different User in the Same Environment

You can keep the environment of the current user account with the –p option:

$ su –p [other_user]

Replace [other_user] with the actual username you want to switch to.

The user account will switch, but you’ll keep the same home directory. This is useful if you need to run a command as a different user, but you need access to the current user’s data.

comments powered by Disqus