Linux – how to run a command as different user

Often we need to run a command as different users. Some of these users may not even have a login shell (e.g. www-data on Ubuntu Linux). Here are some scenarios of running a command as different user. We’ll use Ubuntu Linux for the purpose of this utorial.

sudo as user using non-login shell

$ whoami
user1
$ pwd
/home/user1/tmp
$ sudo -u www-data pwd
/home/gopj/tmp

sudo as user using its login shell

This will run the shell specified by the target user’s password database entry as a login shell.

$ sudo -i -u user2 pwd
/home/user2

If you do it for a user with no login shell, then you will get an error msg:

$ sudo -i -u www-data pwd
This account is currently not available.

su as user

We can also use su as root user.

$ sudo su -
$ whoami
root
$ su user2 -c pwd
/root

Note that when using non-login shell, user’s environment is set as per ~/.bashrc

su as user with login shell

We can also use su as root user.

$ sudo su -
$ whoami
root
$ su - user2 -c pwd
/home/user2

Note that when using login shell, user’s environment is set as per ~/.bash_profile

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments