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 dosudo -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 ?
Running some parts of a script as an unprivileged user with shell environment
bash;shell;sudo;su
.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.  