有几个地方可以设置环境变量。
~/.profile: use this for variables you want to set in all programs launched from the terminal (note that, unlike on Linux, all shells opened in Terminal.app are login shells).
~/.bashrc: this is invoked for shells which are not login shells. Use this for aliases and other things which need to be redefined in subshells, not for environment variables that are inherited.
/etc/profile: this is loaded before ~/.profile, but is otherwise equivalent. Use it when you want the variable to apply to terminal programs launched by all users on the machine (assuming they use bash).
~/.MacOSX/environment.plist: this is read by loginwindow on login. It applies to all applications, including GUI ones, except those launched by Spotlight in 10.5 (not 10.6). It requires you to logout and login again for changes to take effect. This file is no longer supported as of OS X 10.8.
your user's launchd instance: this applies to all programs launched by the user, GUI and CLI. You can apply changes at any time by using the setenv command in launchctl. In theory, you should be able to put setenv commands in ~/.launchd.conf, and launchd would read them automatically when the user logs in, but in practice support for this file was never implemented. Instead, you can use another mechanism to execute a script at login, and have that script call launchctl to set up the launchd environment.
/etc/launchd.conf: this is read by launchd when the system starts up and when a user logs in. They affect every single process on the system, because launchd is the root process. To apply changes to the running root launchd you can pipe the commands into sudo launchctl.
需要理解的基本事情是:
环境变量在fork时由进程的子进程继承。
根进程是一个launchd实例,每个用户会话还有一个单独的launchd实例。
Launchd允许您使用launchctl更改其当前环境变量;更新后的变量将被它从此以后派生的所有新进程继承。
使用launchd设置环境变量的例子:
echo setenv REPLACE_WITH_VAR REPLACE_WITH_VALUE | launchctl
现在,启动使用该变量的GUI应用程序,瞧!
为了解决~/.launchd.conf不能工作的问题,你可以把下面的脚本放在~/Library/LaunchAgents/local.launchd.conf.plist中:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>local.launchd.conf</string>
<key>ProgramArguments</key>
<array>
<string>sh</string>
<string>-c</string>
<string>launchctl < ~/.launchd.conf</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
然后你可以在~/.launchd.conf中放入setenv REPLACE_WITH_VAR REPLACE_WITH_VALUE,它将在每次登录时执行。
请注意,当以这种方式将命令列表管道到launchctl中时,您将不能设置包含空格的值的环境变量。如果你需要这样做,你可以调用launchctl,如下所示:
另外,请注意,在登录时运行的其他程序可能在启动代理之前执行,因此可能看不到它设置的环境变量。