【问题标题】:source /etc/profile within bash scriptbash 脚本中的源 /etc/profile
【发布时间】:2016-08-18 18:40:05
【问题描述】:

我有一个 bash 脚本,它将 rbenv 安装到 /usr/local 并将所需的环境变量添加到 /etc/profile。我的用户是root:

#!/bin/bash

exec {log_fd}>log.txt

git clone https://github.com/rbenv/rbenv.git /usr/local/rbenv >&$log_fd 2>&1
git clone https://github.com/rbenv/ruby-build.git /usr/local/rbenv/plugins/ruby-build >&$log_fd 2>&1
echo 'export RBENV_ROOT=/usr/local/rbenv' >> /etc/profile >&$log_fd 2>&1
echo 'export PATH="/usr/local/rbenv/bin:$PATH"' >> /etc/profile >&$log_fd 2>&1
echo 'if which rbenv > /dev/null; then eval "$(rbenv init - --no-rehash)"; fi' >> /etc/profile >&$log_fd 2>&1
. /etc/profile

但是,PATH 变量没有按应有的方式导出,但 RBENV_ROOT 是!

~#: printenv
RBENV_ROOT=/usr/local/rbenv
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
MAIL=/var/mail/root
LANG=en_US.UTF-8
RBENV_SHELL=bash

我希望看到 /usr/local/rbenv/ 作为 PATH 的一部分,对吧?

我也尝试过切换添加路径的语法,但这也无济于事:

echo 'export PATH=$PATH:/usr/local/rbenv/bin' >> /etc/profile 2>&1

如果您想知道,我正在重定向输出,因为这都在一个whiptail 菜单中。

那么,为什么会显示一个变量 RBENV_ROOT 而不是我应该更新的 PATH

【问题讨论】:

    标签: linux bash ubuntu rbenv


    【解决方案1】:

    序列>>/etc/profile >&$log_fd 2>&1 导致echo 运行,stdout 和stderr 重定向到文件描述符$log_fd,而不是/etc/profile。这是因为在这种情况下,重定向是从左到右处理的,当涉及到标准输出时,第二个会覆盖第一个。看到这个:

    #!/bin/bash
    exec {fd}>/tmp/file1
    echo 'hello' >>/tmp/file2 >&$fd 2>&1
    

    使这个可执行文件,运行它,然后检查hello 是否只出现在/tmp/file1 中。

    当然,这并不能解释为什么设置了RBENV_ROOT 。也许您将它设置在其他启动文件中?

    至于使用 echo 'export PATH=$PATH:/usr/local/rbenv/bin' >>/etc/profile',我可以确认,如果我在 Ubuntu 14.04 上这样做,我会看到新目录是 PATH 的一部分,正如预期的那样。但是,要查看更改,您必须确保获得了 /etc/profile 的来源,这仅在您启动登录 shell 时才会发生。例如,env -i bash -lc 'echo $PATH'

    【讨论】:

    • 这就是我正在处理的问题...我可以从同一个脚本中获取它,这样我就不必启动新的登录 shell 了吗?
    • 可以rbenv init - --no-rehash重置PATH吗?!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 2018-12-04
    • 2013-04-07
    • 2018-03-10
    • 2016-12-03
    相关资源
    最近更新 更多