0

I have a bash script where at some point, I want to source the ${HOME}/.profile file which should add ${HOME}/.local/bin to the $PATH. But when I check the path with echo $PATH, ${HOME}/.local/bin is absent as if the source did not happen. What am I doing wrong?

if command -v pip3 &>/dev/null; then
    echo "Pip is already installed."
else
    echo "Pip is not installed. Installing Pip..."
    cd ${HOME}/Downloads
    curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
    su -c "python3 get-pip.py --user" "$SUDO_USER"

    cat <<-'EOT' >> "${HOME}/.profile"
    # set PATH so it includes user's private .local/bin if it exists
    if [ -d "$HOME/.local/bin" ] ; then
    PATH="$HOME/.local/bin:$PATH"
    fi
    EOT

    source "${HOME}/.profile"         #this is not happening!!!
    rm ${HOME}/Downloads/get-pip.py
    echo "Pip has been installed."
fi

Thanks in advance.

EDIT: Fixed the script syntax as suggest by Kusalananda.

Stephane B.
  • 542
  • 6
  • 18

1 Answers1

3

A script can't modify the environment of the shell from whence it was executed.

Sourcing ~/.profile in the script will not set the path in the interactive shell that originally started the script. To do that, you would have to source your script.

Also, your here-document would need to be quoted, or the current values of HOME and PATH would be inserted into the .profile file:

cat <<'PROFILE_END' >> "$HOME/.profile"
# set PATH so it includes user's private .local/bin if it exists
if [ -d "$HOME/.local/bin" ] ; then
    PATH="$HOME/.local/bin:$PATH"
fi
PROFILE_END

Also note that if the user is a bash user with an existing ~/.bash_profile file, then the ~/.profile file will be ignored for that user when a new login shell is started.

I'm further unsure why you su to $USER. It seems like an unnecessary step.

Kusalananda
  • 14,885
  • 3
  • 41
  • 52
  • Thanks for your response. I have edited my post. What do you mean by "you would have to source your script"? When I open another shell after the script has run, the path is still not updated although the `~/.local/bin` directory exists. I made it work by appending the lines to `~/.bashrc` instead of `~/.profile`. – Stephane B. May 19 '18 at 15:53
  • @StephaneB. If you want to have the changes to the `.profile` active in the same shell as you run your script from, then you must execute the modification to `PATH` in the same shell environment. This could be done by using `source` on your script. If you have a `~/.bash_profile` file, the `~/.profile` file will not be used (as I mentioned). – Kusalananda May 19 '18 at 15:58
  • https://stackoverflow.com/questions/1464253/global-environment-variables-in-a-shell-script helped me to understand better. – Stephane B. May 20 '18 at 21:37