在OS X中修改环境变量如PATH的正确方法是什么?
我看了谷歌一点,找到了三个不同的文件进行编辑:
/etc/paths ~ / . profile ~ / tcshrc
我甚至没有这些文件中的一些,我很确定.tcshrc是错误的,因为OS X现在使用bash。这些变量,特别是PATH,定义在哪里?
我运行的是OS X v10.5 (Leopard)。
在OS X中修改环境变量如PATH的正确方法是什么?
我看了谷歌一点,找到了三个不同的文件进行编辑:
/etc/paths ~ / . profile ~ / tcshrc
我甚至没有这些文件中的一些,我很确定.tcshrc是错误的,因为OS X现在使用bash。这些变量,特别是PATH,定义在哪里?
我运行的是OS X v10.5 (Leopard)。
当前回答
有时候,前面所有的答案都不适用。如果你想在Eclipse或IntelliJ IDEA中访问一个系统变量(如M2_HOME),在这种情况下,唯一适合我的是:
首先(步骤1)编辑/etc/launchd.conf以包含如下一行:“setenv VAR value”,然后(步骤2)重新启动。
简单地修改.bash_profile将不起作用,因为在OS X中应用程序不会像在其他Unix中那样启动;它们不继承父函数的壳变量。其他的修改都不管用了,原因我也不知道。也许有人可以解释一下。
其他回答
更新(2017-08-04)
从macOS 10.12.6 (Sierra)开始,这个方法似乎已经停止在Apache httpd上工作(对于系统和launchctl配置的用户选项)。其他项目似乎没有受到影响。可以想象,这是httpd中的一个bug。
原来的答案
这涉及到OS X 10.10+(特别是10.11+由于无根模式,其中/usr/bin不再可写)。
我在很多地方读到过,使用launchctl setenv PATH <new PATH >来设置PATH变量由于OS X中的一个错误而不起作用(从个人经验来看似乎是正确的)。我发现还有另一种方法可以为非shell启动的应用程序设置PATH:
sudo launchctl config user path <new path>
这个选项记录在launchctl手册页中:
config system | user parameter value Sets persistent configuration information for launchd(8) domains. Only the system domain and user domains may be configured. The location of the persistent storage is an implementation detail, and changes to that storage should only be made through this subcommand. A reboot is required for changes made through this subcommand to take effect. [...] path Sets the PATH environment variable for all services within the target domain to the string value. The string value should conform to the format outlined for the PATH environment variable in environ(7). Note that if a service specifies its own PATH, the service-specific environment variable will take precedence. NOTE: This facility cannot be used to set general environment variables for all services within the domain. It is intentionally scoped to the PATH environment vari- able and nothing else for security reasons.
我已经确认这与从Finder(使用getenv获取PATH)开始的GUI应用程序一起工作。 请注意,您只需要这样做一次,并且更改将在重新启动时保持不变。
除了建议的方法之外,还有一件事需要注意,至少在OS X 10.5 (Leopard)中,launchd.conf中设置的变量将与.profile中的设置合并。我认为这可能对~/. macosx /environment中的设置有效。plist也是,但我还没有验证。
任何Bash启动文件—~/。bashrc,(~ /。bash_profile、~ / . profile。还有一些奇怪的文件,名为~/. macosx /environment。用于GUI应用程序中的环境变量。
很简单:
编辑~ /。对变量进行配置并按如下方式放置
$ vim ~/.profile
在文件中放置:
MY_ENV_VAR =值
保存(:wq) 重启终端(退出并重新打开) 确保这一切都没问题:
$MY_ENV_VAR 美元的价值
/etc/launchd.conf在OS X v10.10 (Yosemite)、OS X v10.11 (El Capitan)、macOS v10.12 (Sierra)或macOS v10.13 (High Sierra)中不使用。
从launchctl手册页:
/etc/launchd.conf file is no longer consulted for subcommands to run during early boot time;
this functionality was removed for security considerations.
这个Ask Different answer中描述的方法适用于我(重启后):从Dock或Spotlight启动的应用程序继承了我在~/Library/LaunchAgents/my.startup.plist中设置的环境变量。(在我的例子中,我需要将LANG设置为en_US。UTF-8,用于Sublime Text插件。)