【问题标题】:Issue with environment variable on Mac OS sierraMac OS sierra 上的环境变量问题
【发布时间】:2019-03-09 21:50:44
【问题描述】:

我发现在 mac os 中存储环境存在一个奇怪的问题。

我在~/.bash_profile 中设置了自定义环境 导出 MYENV=用户 然后运行. ~/.bash_profile 然后我使用打印环境 printenv 然后我可以在列表中看到 MYENV=user。

如果我关闭终端并重新打开并执行printenv,那么我在列表中看不到MYENV,我仍然可以在~/.bash_profile 中看到导出MYENV=user。我觉得很奇怪。

我正在使用 Mac os High Sierra 10.13.6。 有人可以告诉我我在做什么错误吗?

【问题讨论】:

  • 你使用了错误的文件通知~/.bashProfile vs ~/.bash_profile
  • @BradAllred 这是问题中的错字。我更正了。
  • 你可能在使用 iterm 或除了 Terminal.app 之外的其他终端应用程序吗?我记得在启动新 shell 时必须将其中一些应用程序配置为显式读取 .bash_profile
  • 另一个似乎对某些用户有效但对其他用户无效的建议是使用名为.profile 的文件。这是我在我的 mac 上使用的(必须检查,因为我几年前解决了同样的问题)。另请参阅:superuser.com/questions/320065/…

标签: macos environment-variables macos-high-sierra


【解决方案1】:

请注意,~/.bash_profile 仅针对登录 shell 运行。从手册页:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and exe- cutes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

因此,如果您的终端没有启动带有-l--login 或带有前导连字符的$0 的shell,它将不是登录shell,因此不会读取~/。 bash_profile。如果您希望 shell 读取该配置脚本,您可能需要重新配置终端启动 shell 的方式。

另一方面,~/.bashrc 总是由交互式 shell 读取。因此,如果您将导出放在该脚本中,它应该会按照您的预期进行。它当然适合我。你回复阿米拉说它不适合你。所以我建议做一个简单的实验。打开两个终端窗口。在一次编辑 ~/.bashrc 并添加这两行:

echo running .bashrc export WTF=abc

在另一个窗口中运行bash。它应该回显该消息并且echo $WTF 应该打印abc。现在打开一个新的终端窗口。如果您没有看到该消息并且 env var 不存在,那么某些东西正在阻止读取该配置脚本。可能正在使用 --norc 标志运行 shell。

【讨论】:

  • 很遗憾,您不正确。这是关于 Mac OS 上的 Terminal.app,它读取 .bash_profile 然后打开一个新窗口,而不是 .bashrc,而不是登录
  • @rje 你只是部分正确。 Terminal.app 所做的总是通过在 shell 名称前加上连字符来启动登录 shell。您似乎没有完全理解术语“登录外壳”的含义。此外,Terminal.app 不是唯一可能的终端。许多人,包括我自己,在 macOS 上使用 iTerm2,它提供了更丰富的行为集。
  • 我不是在谈论登录外壳。我完全知道 Terminal.app 将 bash 作为登录 shell 运行。我只是澄清一下,它在打开新窗口时运行,而不是在用户登录系统时运行。
【解决方案2】:

~/.bash_profile 在初始命令提示符返回给用户之前执行,这意味着在新登录之后。请尝试将环境变量添加到 ~/.bashrc

【讨论】:

  • 感谢您的回复,但没有帮助
  • Mac OS 上的 Terminal.app 不读取 .bashrc 而只读取 .bash_profile
猜你喜欢
  • 2017-07-08
  • 2019-02-15
  • 2011-08-30
  • 1970-01-01
  • 2011-10-23
  • 1970-01-01
  • 2010-10-10
  • 2013-05-04
相关资源
最近更新 更多