Run Command as Another User in Linux Using sudo -u

Quick Linux Tip #131:

Question: How do I run a single command as the mysql user?

Try: sudo -u mysql -H bash -c 'echo $HOME && mysql -e "SHOW DATABASES"'

Info: Runs commands as another user with an updated HOME environment variable.

Examples:

  • $ sudo -u www-data php -r 'echo getcwd();'  # Run a snippet as the web server user
  • $ sudo -u nobody id  # Inspect UID and GID for a restricted user
  • $ sudo -iu postgres  # Open an interactive login shell as postgres

Note: Using -H ensures tools that read user configuration files from HOME behave as expected, while -i simulates a full login environment. Prefer sudo over su - in scripts for clearer audit logging and non-interactive execution.




LinuxTeck.com
linuxteck:~$ sudo -u mysql -H bash -c 'echo $HOME && mysql -e "SHOW DATABASES"'
/var/lib/mysql
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| production_db      |
| sys                |
+--------------------+

linuxteck:~$ sudo -u postgres psql -c '\du'
                              List of roles
 Role name |                         Attributes                  | Member of
-----------+------------------------------------------------------+-----------
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 webapp    | Create DB                                            | {}
linuxteck:~$

PREVIOUS ARTICLE Quick Linux Tip #130: HTTPie API Debugging: Test and Inspect HTTP Requests
About John Britto

John Britto Founder & Chief-Editor @LinuxTeck. A Computer Geek and Linux Intellectual having more than 20+ years of experience in Linux and Open Source technologies.

View all posts by John Britto →

Leave a Reply

Your email address will not be published.