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
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:
whoami
ubuntu
It prints your own user name. On this computer, that’s ubuntu.
Step 2: Run a Command as root
sudo whoami
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
sudo -u nobody whoami
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
| Mistake | What happens | Do this instead |
|---|---|---|
Putting -u after the command, as in sudo whoami -u nobody | The command gets the option and rejects it: error: unexpected argument '-u' found | Put -u and the user right after sudo, before the command. |
| Naming a user that doesn’t exist | sudo: user 'nosuchuser' not found | Check 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.
0 comments