I am creating an instance configuration script that sets up a machine.

I am running the script via sudo i.e. sudo run.sh. Most of the steps require root access but some of the script's steps do no require root access and I prefer running them as the unprivileged user who ran the sudo.

Inside the script running with sudo, I am trying to do

sudo -i -u username sh -c 'echo $MY_ENV'

Since .bashrc contains export MY_ENV=something I expect the above command to print "something"

How can I temporarily switch inside the script to the other user to run commands that include the user's shell env ?

  • possible duplicate of su options - running command as another user
    – jasonwryan
    Apr 11 '15 at 7:46
  • @jasonwryan I've seen that but it says nothing about including the user's env vars as well
    – Michael
    Apr 11 '15 at 7:48
  • @Michael: Take a look at su's option -.
    – Cyrus
    Apr 11 '15 at 8:24
  • Try removing "sh -c" arguments.
    – Andy
    Apr 11 '15 at 10:25
  • @jasonwryan - This isn't about sudo or su, I think. Michael - when you call sh you don't get bashrc doing anything - even if sh is a link to bash. You can do ENV=~/.bashrc sh -c 'cmd' though, maybe. A possible issue with that though is sudo. You can do sudo env - ENV=~/.bashrc sh -c 'cmd. Though I'm not positive if it will correctly work with -c - have to check that. Oh. jasonwryan - maybe it is about sudo after rereading the question. I guess we're talking about .bashrc influencing the command before it is run, not a shell's init file.
    – mikeserv
    Apr 11 '15 at 10:51

.bashrc is executed only by interactive shells, not by scripts¹. It's the wrong place to define environment variables. See Is there a ".bashrc" equivalent file read by all shells? and the Ubuntu wiki.

You can tell bash to read .bashrc explicitly. Of course you'll have to execute bash, not sh which could be a different shell:

sudo -i -u username bash -c '. `~/.bashrc; echo "$MY_ENV"'

But it's a bad idea because .bashrc files are likely to contain things that assume that they're executed on a terminal and that spend time setting up key bindings, aliases, prompts, etc.

The sane solution is to put environment variable definitions where they belong, in ~/.profile or ~/.pam_environment.

¹ Except when bash is called by sshd for some weird reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.