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.
Leave a Reply