To run a single command as another user, use sudo -u:
sudo -u deploy whoami
The common real cases
sudo -u postgres psql # run a DB client as the DB's own user
sudo -u www-data php artisan migrate # run an app command as the web user
sudo -u deploy bash -c 'cd ~ && ./deploy.sh' # a small script as the deploy userRunning as the service's own user matters because files the command creates end up owned correctly. Running a web app's CLI as root, then having the web server (as www-data) unable to read the files it just wrote, is a classic self-inflicted permissions bug.
sudo -u a service account with no login shell
Service accounts often have nologin as their shell, so you cannot su into them interactively. sudo -u does not need a login shell, so it still works:
sudo -u appsvc /opt/app/bin/worker --onceThat runs the worker as appsvc even though nobody can log in as appsvc.
sudo -u vs su vs runuser
| Command | Needs | Runs as | Notes |
|---|---|---|---|
sudo -u user cmd | your sudo rights | target user | Per-command, audited, no target password. The usual choice. |
su - user -c 'cmd' | the target user's password (or root) | target user | Starts a login shell; needs the target's password unless you are root. |
runuser -u user -- cmd | root | target user | Like su but no PAM password prompt; for scripts run as root. |
sudo -u is the right tool interactively because it uses your credentials and is logged. runuser is the scripting tool when you are already root and want no prompt.
Get an interactive shell as the user
sudo -u deploy -i # an interactive login shell as deploy
sudo -u deploy -s # a non-login shell as deploy-i simulates a full login (loads their environment and dotfiles); -s just starts a shell with the current environment.
FAQ
See also
- How to give a user sudo access: the rights that make sudo -u work.
- How to create a user on Linux: service accounts with nologin shells.
- How to edit the sudoers file safely (visudo): scope who may run as whom.
- How to set up passwordless sudo: unattended sudo -u in scripts.
Sources
Authoritative references this article was fact-checked against.





