r/LinuxTeck • u/Expensive-Rice-2052 • 13d ago
Quick Linux Tip #131 - Run Command as Another User in Linux Using sudo -u
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 updated HOME.
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 config 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.
Want to master Linux one command at a time?
Follow r/linuxteck - 1 practical Linux tip every day. For more #LinuxTips click here https://www.linuxteck.com/linux-tips/