sudo to a different user and run command as that user

user1874594 picture user1874594 · Feb 12, 2014 · Viewed 12.5k times · Source

consider this sudo command below

sudo -iu bigadmin

bigadmin is a generic user that all users sudo to, to do stuff with privileged access. Now the problem is it a shared user like I mentioned. So any kind of profile customization isn't gonna work .

What I am trying to do is for the sessions I establish- I want to run a script that has all my variables inside. so when I sudo it should do these things

sudo -iu bigadmin ; . ./mycustomshell.sh 

How's this best done.

Answer

chepner picture chepner · Feb 12, 2014

First, make sure that all the variables in mycustomshell.sh are exported. Then, source it first, then run sudo -iu bigadmin, so that the shell started by sudo inherits the variables exported by mycustomshell.

Another option is to invoke bash as

sudo -iu bigadmin bash --rcfile mycustomshell.sh

However, this causes bash to ignore .bashrc, so you may want to source .bashrc explicitly at the beginning of mycustomershell.sh to compensate.