Skip to main content
0 reactions

How to Run a Command as Another User on Ubuntu (sudo -u)

Featured card for How to Run a Command as Another User on Ubuntu. A terminal window shows whoami printing ubuntu, sudo whoami printing root, and sudo -u nobody whoami printing nobody.
Run a command as another user with sudo -u.

Some commands have to run as a particular user, such as the account a database or a web server runs under. On Ubuntu, sudo -u runs any command as another user.

This guide uses whoami, a command that prints the name of the user it runs as, so you can see the switch happen. Every command and output on this page is real, from Ubuntu 26.04 LTS, where sudo is sudo-rs, a memory-safe rewrite of the original sudo.

Syntax

SyntaxBash
sudo -u <user> <command>
  • sudo: runs a command as another user. On its own, it runs the command as root, the administrator.
  • -u <user>: the user to run the command as, instead of root.
  • <command>: the command to run, with any options of its own. It always comes after the user.

These parts come from sudo’s manual page (opens in a new tab) for Ubuntu 26.04.

Prerequisites

  • A user account that can run commands with sudo.

Step 1: Check Which User You Are

Open a terminal and run:

Ubuntu TerminalBash
whoami
OutputPlain text
ubuntu

It prints your own user name. On this computer, that’s ubuntu.

Step 2: Run a Command as root

Ubuntu TerminalBash
sudo whoami
OutputPlain text
root

Without -u, sudo runs the command as root. If Ubuntu asks for your password, type it and press Enter.

Step 3: Run a Command as Another User on Ubuntu

Ubuntu TerminalBash
sudo -u nobody whoami
OutputPlain text
nobody

This time whoami ran as nobody, a built-in account that can’t log in. In real work you swap in the user and the command you need. For example, sudo -u postgres psql opens PostgreSQL as its own postgres user, as How to Install PostgreSQL 19 on Ubuntu shows.

Common Mistakes

MistakeWhat happensDo this instead
Putting -u after the command, as in sudo whoami -u nobodyThe command gets the option and rejects it: error: unexpected argument '-u' foundPut -u and the user right after sudo, before the command.
Naming a user that doesn’t existsudo: user 'nosuchuser' not foundCheck the spelling of the user name.

FAQ

What’s the difference between sudo and sudo -u?

sudo on its own runs a command as root. sudo -u runs it as the user you name.

Does sudo -u work the same with sudo-rs?

Yes. Ubuntu 26.04’s sudo is sudo-rs, and its manual describes -u the same way: run the command as another user than the default, root.

Conclusion

sudo -u <user> <command> runs one command as another user and returns you to your own account when it ends. Put the user right after -u, and the command after that.

Additional Resources

0 comments