This question already has an answer here:

Take the following ~/test.sh script as an example:


sudo -u ${SUDO_USER} cp ~/.profile ~/.profile.bak

cat <<EOF >>/home/${SUDO_USER}/.profile
export HELLO="Hello StackExchange"

sudo -u ${SUDO_USER} source ~/.profile

sudo -u ${SUDO_USER} cp ~/.profile.bak ~/.profile
sudo -u ${SUDO_USER} rm ~/.profile.bak

I then run it like this:

User@MACHINE:~$ sudo bash test.sh
User@MACHINE:~$ echo $HELLO

I was expecting Hello StackExchange to be printed on the terminal, but a blank line was printed instead.

If I understand what's happening correctly, the source ~/.profile command is not being applied to my current shell. So how I can source changes done to files like .profile to the current running shell from a script without having to logout and log back in? Is this even possible?

P.S: Assume test.sh is always ran with sudo and never without it. The script above is just an example, but I use sudo -u ${SUDO_USER} command when I need certain commands to run as the user who invoked the script and not as root.

marked as duplicate by Rui F Ribeiro, Kusalananda bash Apr 15 '18 at 11:47

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Why are you using SUDO_USER with su? – Rui F Ribeiro Apr 15 '18 at 11:26
  • @RuiFRibeiro Not sure what you mean... – Ricardo Amaral Apr 15 '18 at 11:28
  • @RuiFRibeiro When I run sudo bash test.sh the user inside the script will be root and $SUDO_USER gives me my username Ricardo which I need to specify the user I want su to run with. I'm in the process of replacing the su calls with sudo, makes for clearer commands (I'll edit the question in a few seconds). But the problem persists – Ricardo Amaral Apr 15 '18 at 11:33
  • That is expected sudo behaviour – Rui F Ribeiro Apr 15 '18 at 11:42
  • 1
    You seem to be working on the same thing as in this question: unix.stackexchange.com/questions/437872/… See my answer there. – Kusalananda Apr 15 '18 at 11:48