在OS X中修改环境变量如PATH的正确方法是什么?

我看了谷歌一点,找到了三个不同的文件进行编辑:

/etc/paths ~ / . profile ~ / tcshrc

我甚至没有这些文件中的一些,我很确定.tcshrc是错误的,因为OS X现在使用bash。这些变量,特别是PATH,定义在哪里?

我运行的是OS X v10.5 (Leopard)。


当前回答

对于Bash,尝试将环境变量添加到文件/etc/profile中,以使它们对所有用户可用。不需要重新启动,只需启动一个新的终端会话。

其他回答

另一个免费、开源的Mac OS X v10.8 (Mountain Lion)首选项窗格/环境。plist解决方案是EnvPane。

EnvPane的源代码可在GitHub。EnvPane看起来具有与rcenvirenvironment相当的功能,然而,它似乎可以立即更新其存储的变量,即不需要重新启动或登录,这是受欢迎的。

如开发商所述:

EnvPane is a preference pane for Mac OS X 10.8 (Mountain Lion) that lets you set environment variables for all programs in both graphical and terminal sessions. Not only does it restore support for ~/.MacOSX/environment.plist in Mountain Lion, it also publishes your changes to the environment immediately, without the need to log out and back in. <SNIP> EnvPane includes (and automatically installs) a launchd agent that runs 1) early after login and 2) whenever the ~/.MacOSX/environment.plist changes. The agent reads ~/.MacOSX/environment.plist and exports the environment variables from that file to the current user's launchd instance via the same API that is used by launchctl setenv and launchctl unsetenv.

免责声明:我与开发者或他/她的项目没有任何关系。

附注:我喜欢这个名字(听起来像“Ends Pain”)。

这很简单。编辑文件.profile (vi, nano, Sublime Text或其他文本编辑器)文件。你可以在~/目录(用户目录)中找到它,并像这样设置:

export MY_VAR=[your value here]

Java home的示例:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/current

保存它并返回到终端。

你可以用:

source .profile

或者关闭并打开终端窗口。

直到和包括OS X v10.7 (Lion),你可以设置它们:

~/.MacOSX/environment.plist

See:

https://developer.apple.com/legacy/library/qa/qa1067/_index.html https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html

对于终端中的PATH,您应该能够在.bash_profile或.profile中设置(尽管您可能必须创建它)

对于OS X v10.8 (Mountain Lion)及以上版本,您需要使用launchd和launchctl。

这里有一个非常简单的方法来做你想做的事情。在我的例子中,它是让Gradle工作(Android Studio)。

打开终端。 执行如下命令: Sudo nano /etc/paths或Sudo vim /etc/paths 在提示时输入密码。 转到文件底部,输入要添加的路径。 点击Control + X退出。 输入“Y”保存修改后的缓冲区。 打开一个新的终端窗口,然后输入: 回声路径美元

您应该看到新路径被追加到path的末尾。

我从这篇文章中得到了这些细节:

添加到Mac OS X 10.8 Mountain Lion及以上版本的PATH中

这里有两种类型的炮弹。

非登录:每次启动一个新的Bash副本时,.bashrc都会被重新加载 登录:.profile只有在登录或显式告诉Bash加载它并将其用作登录shell时才会被加载。

在这里,重要的是要理解在Bash中,.bashrc文件只能由交互式和非登录的shell读取,您会发现人们经常在.bash_profile中加载.bashrc以克服这一限制。

现在您已经有了基本的了解,让我们继续讨论我建议您如何设置它。

.profile:创建一个不存在的文件。把你的PATH设置放在那里。 .bashrc:如果不存在则创建。把你所有的别名和自定义方法都放进去。 .bash_profile:如果不存在则创建。把下面的东西放进去。

.bash_file:

#!/bin/bash
source ~/.profile # Get the PATH settings
source ~/.bashrc  # Get Aliases and Functions
#