我有一个将 rbenv
安装到 /usr/local
并将所需的环境变量添加到 /etc/profile
的 bash 脚本。我的用户是 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
如果您想知道,我正在重定向输出,因为这都在鞭尾菜单中。
那么,为什么会显示一个变量 RBENV_ROOT
而不是我应该更新的 PATH
?
最佳答案
序列 >>/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'
。
关于linux - bash 脚本中的 source/etc/profile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39025347/