为什么我的文件不是从bash脚本获取的?

时间:2018-05-19 10:38:39

标签: bash shell

我有一个bash脚本,在某些时候,我想要获取${HOME}/.profile文件,该文件应该将${HOME}/.local/bin添加到$ PATH。但是当我使用echo $PATH检查路径时,${HOME}/.local/bin缺席,就好像源没有发生一样。我做错了什么?

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

提前致谢。

编辑:修正了Kusalananda建议的脚本语法。

1 个答案:

答案 0 :(得分:3)

脚本无法修改shell的执行环境。

在脚本中搜索~/.profile将不会在最初启动脚本的交互式shell中设置路径。要做到这一点,你必须 source 你的脚本。

此外,您的here-document需要引用,或者HOMEPATH当前值将插入到.profile文件中:

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

另请注意,如果用户是具有现有bash文件的~/.bash_profile用户,则在启动新的登录shell时,该用户将忽略~/.profile文件。 / p>

我进一步不确定你su$USER的原因。这似乎是一个不必要的步骤。

相关问题