Run command as another user

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-04-18

Option 1: With sudo

If you start off as not root, this is a good option

sudo -u www-data -i -- wp plugin --path=/var/www/html activate s3-uploads

Explanation:

Option 2: With su

If you start off as root (instead of someone else) you can use su to run a command as someone else

su -c "wp plugin --path=/var/www/html activate s3-uploads" www-data

Explanation:

Downsides of su:

The su version has limitations, in that it always executes the shell listed in /etc/passwd, therefore is incompatible e.g. with /usr/sbin/nologin

Therefore if I had this entry for www-data then I'd be unable to login and therefore unable to use su. Sure enough this happened:

www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin

This can be fixed by changing the shell for that user to be one that permits log in.

chsh -s /bin/bash www-data