在OS X上设置环境变量

时间:2022-03-29 01:25:33

What is the proper way to modify environment variables like PATH in OS X?

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

I've looked on Google a little bit and found three different files to edit:

我在Google上看了一下,发现了三个不同的文件要编辑:

  • /etc/paths
  • ~/.profile
  • ~/.tcshrc

I don't even have some of these files, and I'm pretty sure that .tcshrc is wrong, since OS X uses bash now. Where are these variables, especially PATH, defined?

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

I'm running OS X v10.5 (Leopard).

我正在运行OS X v10.5(Leopard)。

30 个解决方案

#1


618  

Bruno is right on track. I've done extensive research and if you want to set variables that are available in all GUI applications, your only option is /etc/launchd.conf.

布鲁诺正好走上正轨。我做了大量的研究,如果你想设置所有GUI应用程序中可用的变量,你唯一的选择是/etc/launchd.conf。

Please note that environment.plist does not work for applications launched via Spotlight. This is documented by Steve Sexton here.

请注意,environment.plist不适用于通过Spotlight启动的应用程序。史蒂夫塞克斯顿在这里记录了这一点。

  1. Open a terminal prompt

    打开终端提示

  2. Type sudo vi /etc/launchd.conf (note: this file might not yet exist)

    输入sudo vi /etc/launchd.conf(注意:此文件可能尚不存在)

  3. Put contents like the following into the file

    将以下内容放入文件中

    # Set environment variables here so they are available globally to all apps
    # (and Terminal), including those launched via Spotlight.
    #
    # After editing this file run the following command from the terminal to update
    # environment variables globally without needing to reboot.
    # NOTE: You will still need to restart the relevant application (including
    # Terminal) to pick up the changes!
    # grep -E "^setenv" /etc/launchd.conf | xargs -t -L 1 launchctl
    #
    # See http://www.digitaledgesw.com/node/31
    # and http://*.com/questions/135688/setting-environment-variables-in-os-x/
    #
    # Note that you must hardcode the paths below, don't use environment variables.
    # You also need to surround multiple values in quotes, see MAVEN_OPTS example below.
    #
    setenv JAVA_VERSION 1.6
    setenv JAVA_HOME /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
    setenv GROOVY_HOME /Applications/Dev/groovy
    setenv GRAILS_HOME /Applications/Dev/grails
    setenv NEXUS_HOME /Applications/Dev/nexus/nexus-webapp
    setenv JRUBY_HOME /Applications/Dev/jruby
    
    setenv ANT_HOME /Applications/Dev/apache-ant
    setenv ANT_OPTS -Xmx512M
    
    setenv MAVEN_OPTS "-Xmx1024M -XX:MaxPermSize=512m"
    setenv M2_HOME /Applications/Dev/apache-maven
    
    setenv JMETER_HOME /Applications/Dev/jakarta-jmeter
    
  4. Save your changes in vi and reboot your Mac. Or use the grep/xargs command which is shown in the code comment above.

    在vi中保存更改并重新启动Mac。或者使用上面代码注释中显示的grep / xargs命令。

  5. Prove that your variables are working by opening a Terminal window and typing export and you should see your new variables. These will also be available in IntelliJ IDEA and other GUI applications you launch via Spotlight.

    通过打开终端窗口并键入export来证明您的变量正常工作,您应该看到新的变量。这些也可以在您通过Spotlight启动的IntelliJ IDEA和其他GUI应用程序中使用。

#2


245  

How to set the environment for new processes started by Spotlight (without needing to reboot)

You can set the environment used by launchd (and, by extension, anything started from Spotlight) with launchctl setenv. For example to set the path:

您可以使用launchctl setenv设置launchd(以及扩展名,从Spotlight启动的任何内容)使用的环境。例如,设置路径:

launchctl setenv PATH /opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin

Or if you want to set up your path in .bashrc or similar, then have it mirrored in launchd:

或者,如果要在.bashrc或类似路径中设置路径,请将其镜像到launchd中:

PATH=/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin
launchctl setenv PATH $PATH

There's no need to reboot though you will need to restart an app if you want it to pick up the changed environment.

没有必要重新启动,但如果您希望它能够获取更改的环境,则需要重新启动应用程序。

This includes any shells already running under Terminal.app, although if you're there you can set the environment more directly, e.g. with export PATH=/opt/local/bin:/opt/local/sbin:$PATH for bash or zsh.

这包括已经在Terminal.app下运行的所有shell,但如果你在那里,你可以更直接地设置环境,例如with export PATH = / opt / local / bin:/ opt / local / sbin:$ PATH for bash或zsh。

How to keeping changes after a reboot

To keep changes after a reboot you can set the environment variables from /etc/launchd.conf, like so:

要在重新启动后保持更改,可以在/etc/launchd.conf中设置环境变量,如下所示:

setenv PATH /opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin

launchd.conf is executed automatically when you reboot.

重启时会自动执行launchd.conf。

If you want these changes to take effect now, you should use this command to reprocess launchctl.conf (thanks @mklement for the tip!)

如果您希望这些更改现在生效,您应该使用此命令重新处理launchctl.conf(感谢@mklement提示!)

egrep -v '^\s*#' /etc/launchd.conf | launchctl

You can find out more about launchctl and how it loads launchd.conf with the command man launchctl.

您可以使用命令man launchctl找到有关launchctl及其如何加载launchd.conf的更多信息。

#3


104  

Up to and including OS X v10.7 (Lion) you can set them in:

在OS X v10.7(Lion)中,您可以将它们设置为:

~/.MacOSX/environment.plist

See:

For PATH in the Terminal, you should be able to set in .bash_profile or .profile (you'll probably have to create it though)

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

For OS X v10.8 (Mountain Lion) and beyond you need to use launchd and launchctl.

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

#4


56  

Solution for both command line and GUI apps from a single source (works with Yosemite & El Capitan)

Let's assume you have environment variable definitions in your ~/.bash_profile like in the following snippet:

假设您在〜/ .bash_profile中有环境变量定义,如下面的代码片段所示:

export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"
export GOPATH="$HOME/go"
export PATH="$PATH:/usr/local/opt/go/libexec/bin:$GOPATH/bin"
export PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
export MANPATH="/usr/local/opt/coreutils/libexec/gnuman:$MANPATH"

We need a Launch Agent which will run on each login and anytime on demand which is going to load these variables to the user session. We'll also need a shell script to parse these definitions and build necessary commands to be executed by the agent.

我们需要一个启动代理,它将在每次登录时随时随地运行,并将这些变量加载到用户会话。我们还需要一个shell脚本来解析这些定义并构建由代理执行的必要命令。

Create a file with plist suffix (e.g. named osx-env-sync.plist) in ~/Library/LaunchAgents/ directory with the following contents:

在〜/ Library / LaunchAgents /目录中创建一个带有plist后缀的文件(例如命名为osx-env-sync.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>osx-env-sync</string>
  <key>ProgramArguments</key>
  <array>
    <string>bash</string>
    <string>-l</string>
    <string>-c</string>
    <string>
      $HOME/.osx-env-sync.sh
    </string>
  </array>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>

-l parameter is critical here; it's necessary for executing the shell script with a login shell so that ~/.bash_profile is sourced in the first place before this script is executed.

-l参数在这里至关重要;使用登录shell执行shell脚本是必要的,以便在执行此脚本之前首先获取〜/ .bash_profile。

Now, the shell script. Create it at ~/.osx-env-sync.sh with the following contents:

现在,shell脚本。使用以下内容在〜/ .osx-env-sync.sh创建它:

grep export $HOME/.bash_profile | while IFS=' =' read ignoreexport envvar ignorevalue; do
  launchctl setenv ${envvar} ${!envvar}
done

Make sure the shell script is executable:

确保shell脚本是可执行的:

chmod +x ~/.osx-env-sync.sh

Now, load the launch agent for current session:

现在,加载当前会话的启动代理:

launchctl load ~/Library/LaunchAgents/osx-env-sync.plist

(Re)Launch a GUI application and verify that it can read the environment variables.

(重新)启动GUI应用程序并验证它是否可以读取环境变量。

The setup is persistent. It will survive restarts and relogins.

设置是持久的。它将在重新启动和重新运行后继续存在。

After the initial setup (that you just did), if you want to reflect any changes in your ~/.bash_profile to your whole environment again, rerunning the launchctl load ... command won't perform what you want; instead you'll get a warning like the following:

在初始设置之后(您刚刚进行了设置),如果您希望将〜/ .bash_profile中的任何更改再次反映到整个环境中,则重新运行launchctl load ...命令将无法执行您想要的操作;相反,你会收到如下警告:

<$HOME>/Library/LaunchAgents/osx-env-sync.plist: Operation already in progress

<$ HOME> /Library/LaunchAgents/osx-env-sync.plist:操作已在进行中

In order to reload your environment variables without going through the logout/login process do the following:

要在不经过注销/登录过程的情况下重新加载环境变量,请执行以下操作:

launchctl unload ~/Library/LaunchAgents/osx-env-sync.plist
launchctl load ~/Library/LaunchAgents/osx-env-sync.plist

Finally make sure that you relaunch your already running applications (including Terminal.app) to make them aware of the changes.

最后确保重新启动已经运行的应用程序(包括Terminal.app),以使他们了解更改。

I've also pushed the code and explanations here to a GitHub project: osx-env-sync.

我还将代码和解释推送到GitHub项目:osx-env-sync。

I hope this is going to be the ultimate solution, at least for the latest versions of OS X (Yosemite & El Capitan).

我希望这将是最终解决方案,至少对于最新版本的OS X(Yosemite和El Capitan)而言。

#5


47  

1.

vim ~/.bash_profile

The file may not exist (if not, you can just create it).

该文件可能不存在(如果没有,您可以创建它)。

2.type in this and save the file:

2.在此输入并保存文件:

export PATH=$PATH:YOUR_PATH_HERE

3.run

source ~/.bash_profile

#6


35  

There are essentially two problems to solve when dealing with environment variables in OS X. The first is when invoking programs from Spotlight (the magnifying glass icon on the right side of the Mac menu/status bar) and the second when invoking programs from the Dock. Invoking programs from a Terminal application/utility is trivial because it reads the environment from the standard shell locations (~/.profile, ~/.bash_profile, ~/.bashrc, etc.)

在OS X中处理环境变量时,基本上有两个问题需要解决。第一个是从Spotlight调用程序(Mac菜单/状态栏右侧的放大镜图标),第二个是从Dock调用程序时。从终端应用程序/实用程序调用程序是微不足道的,因为它从标准shell位置读取环境(〜/ .profile,〜/ .bash_profile,〜/ .bashrc等)

When invoking programs from the Dock, use ~/.MacOSX/environment.plist where the <dict> element contains a sequence of <key>KEY</key><string>theValue</string> elements.

从Dock调用程序时,使用〜/ .MacOSX / environment.plist,其中<​​dict>元素包含 KEY theValue 元素的序列。

When invoking programs from Spotlight, ensure that launchd has been setup with all the key/value settings you require.

从Spotlight调用程序时,请确保已使用所需的所有键/值设置设置launchd。

To solve both problems simultaneously, I use a login item (set via the System Preferences tool) on my User account. The login item is a bash script that invokes an Emacs lisp function although one can of course use their favorite scripting tool to accomplish the same thing. This approach has the added benefit that it works at any time and does not require a reboot, i.e. one can edit ~/.profile, run the login item in some shell and have the changes visible for newly invoked programs, from either the Dock or Spotlight.

要同时解决这两个问题,我在用户帐户上使用登录项(通过“系统首选项”工具设置)。登录项是一个调用Emacs lisp函数的bash脚本,尽管当然可以使用他们喜欢的脚本工具来完成同样的事情。这种方法有额外的好处,它可以在任何时候工作,不需要重新启动,即可以编辑〜/ .profile,在某些shell中运行登录项,并对Dock中的新调用的程序进行更改。聚光灯。

Details:

Login item: ~/bin/macosx-startup

登录项目:〜/ bin / macosx-startup

#!/bin/bash
bash -l -c "/Applications/Emacs.app/Contents/MacOS/Emacs --batch -l ~/lib/emacs/elisp/macosx/environment-support.el -f generate-environment"

Emacs lisp function: ~/lib/emacs/elisp/macosx/envionment-support.el

Emacs lisp函数:〜/ lib / emacs / elisp / macosx / envionment-support.el

;;; Provide support for the environment on Mac OS X

(defun generate-environment ()
  "Dump the current environment into the ~/.MacOSX/environment.plist file."
  ;; The system environment is found in the global variable:
  ;; 'initial-environment' as a list of "KEY=VALUE" pairs.
  (let ((list initial-environment)
        pair start command key value)
    ;; clear out the current environment settings
    (find-file "~/.MacOSX/environment.plist")
    (goto-char (point-min))
    (setq start (search-forward "<dict>\n"))
    (search-forward "</dict>")
    (beginning-of-line)
    (delete-region start (point))
    (while list
      (setq pair (split-string (car list) "=")
            list (cdr list))
      (setq key (nth 0 pair)
            value (nth 1 pair))
      (insert "  <key>" key "</key>\n")
      (insert "  <string>" value "</string>\n")

      ;; Enable this variable in launchd
      (setq command (format "launchctl setenv %s \"%s\"" key value))
      (shell-command command))
    ;; Save the buffer.
    (save-buffer)))

NOTE: This solution is an amalgam of those coming before I added mine, particularly that offered by Matt Curtis, but I have deliberately tried to keep my ~/.bash_profile content platform independent and put the setting of the launchd environment (a Mac only facility) into a separate script.

注意:这个解决方案是我加入我的之前的混合物,特别是Matt Curtis提供的那些,但我故意试图保持我的〜/ .bash_profile内容平*立并放置启动环境的设置(仅限Mac设施) )进入一个单独的脚本。

#7


21  

Another, free, opensource, Mac OSX Mountain Lion (10.8) Preference pane/environment.plist solution is EnvPane.

另一个免费的开源Mac OSX Mountain Lion(10.8)Preference pane / environment.plist解决方案是EnvPane。

EnvPane's source code available on Github. EnvPane looks like it has comparable features to RCEnvironment, however, it seems it can update its stored variables instantly, i.e. without the need for a restart or login, which is welcome.

EnvPane的源代码可在Github上获得。 EnvPane看起来具有与RCEnvironment类似的功能,但是,它似乎可以立即更新其存储的变量,即无需重启或登录,这是受欢迎的。

As stated by the developer:

正如开发人员所说:

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.

EnvPane是Mac OS X 10.8(Mountain Lion)的首选项窗格,可让您为图形和终端会话中的所有程序设置环境变量。它不仅可以恢复对Mountain Lion中〜/ .MacOSX / environment.plist的支持,还可以立即发布您对环境的更改,而无需注销并重新登录。 EnvPane包括(并自动安装)在登录后早期运行1)的launchd代理和2)每当〜/ .MacOSX / environment.plist发生更改时。代理读取〜/ .MacOSX / environment.plist,并通过launchctl setenv和launchctl unsetenv使用的相同API将该文件中的环境变量导出到当前用户的launchd实例。

Disclaimer: I am in no way related to the developer or his/her project.

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

P.S. I like the name (sounds like 'Ends Pain').

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

#8


17  

On Mountain Lion all the /etc/paths and /etc/launchd.conf editing doesn't take any effect!

在Mountain Lion上,所有/ etc / paths和/etc/launchd.conf编辑都没有任何效果!

Apple's Developer Forums say:

Apple的开发者论坛说:

"Change the Info.plist of the .app itself to contain an "LSEnvironment" dictionary with the environment variables you want.

“更改.app本身的Info.plist以包含带有所需环境变量的”LSEnvironment“字典。

~/.MacOSX/environment.plist is no longer supported."

不再支持〜/ .MacOSX / environment.plist。“

So I directly edited the app's Info.plist (right click on "AppName.app" (in this case SourceTree) and then "Show package contents")

所以我直接编辑了应用程序的Info.plist(右键单击“AppName.app”(在本例中为SourceTree),然后“显示包内容”)

在OS X上设置环境变量

and added a new key/dict pair called:

并添加了一个名为的新键/ dict对:

<key>LSEnvironment</key>
<dict>
     <key>PATH</key>
     <string>/Users/flori/.rvm/gems/ruby-1.9.3-p362/bin:/Users/flori/.rvm/gems/ruby-1.9.3-p362@global/bin:/Users/flori/.rvm/rubies/ruby-1.9.3-p326/bin:/Users/flori/.rvm/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:</string>
</dict>

(see: LaunchServicesKeys Documentation at Apple)

(请参阅:Apple的LaunchServicesKeys文档)

在OS X上设置环境变量

now the App (in my case SourceTree) uses the given path and works with git 1.9.3 :-)

现在App(在我的情况下是SourceTree)使用给定的路径并使用git 1.9.3 :-)

PS: Of course you have to adjust the Path entry to your specific path needs.

PS:当然,您必须根据特定路径需求调整Path条目。

#9


16  

While the answers here aren't "wrong", I'll add another: never make environment variable changes in OS X that affect "all processes", or even, outside the shell, for all processes run interactively by a given user.

虽然这里的答案并非“错误”,但我将添加另一个:永远不要在OS X中对环境变量进行更改,这些更改会影响“所有进程”,甚至在shell外部,对于给定用户以交互方式运行的所有进程。

In my experience, global changes to environment variables like PATH for all processes are even more likely to break things on OS X than on Windows. Reason being, lots of OS X applications and other software (including, perhaps especially, components of the OS itself) rely on UNIX command-line tools under the hood, and assume the behavior of the versions of these tools provided with the system, and don't necessarily use absolute paths when doing so (similar comments apply to dynamically-loaded libraries and DYLD_* environment variables). Consider, for instance, that the highest-rated answers to various Stack Overflow questions about replacing OS X-supplied versions of interpreters like Python and Ruby generally say "don't do this."

根据我的经验,对于所有进程的环境变量(如PATH)的全局更改甚至更可能破坏OS X而不是Windows。原因是,许多OS X应用程序和其他软件(包括,特别是OS本身的组件)依赖于UNIX命令行工具,并假设系统提供的这些工具的版本行为,以及这样做时不一定使用绝对路径(类似的注释适用于动态加载的库和DYLD_ *环境变量)。例如,考虑一下有关替换OS X提供的解释器版本(如Python和Ruby)的各种Stack Overflow问题的最高评级答案通常会说“不要这样做”。

OS X is really no different than other UNIX-like operating systems (e.g., Linux, FreeBSD, and Solaris) in this respect; the most likely reason Apple doesn't provide an easy way to do this is because it breaks things. To the extent Windows isn't as prone to these problems, it's due to two things: (1) Windows software doesn't tend to rely on command-line tools to the extent that UNIX software does, and (2) Microsoft has had such an extensive history of both "DLL hell" and security problems caused by changes that affect all processes that they've changed the behavior of dynamic loading in newer Windows versions to limit the impact of "global" configuration options like PATH.

在这方面,OS X与其他类UNIX操作系统(例如Linux,FreeBSD和Solaris)没有什么不同;苹果公司没有提供简单方法的最可能原因是因为它打破了局面。在某种程度上,Windows并不容易出现这些问题,这主要归功于两件事:(1)Windows软件不像UNIX软件那样依赖命令行工具,(2)微软已经拥有“DLL地狱”这样一个广泛的历史记录和由影响所有进程的更改引起的安全问题,它们改变了新版Windows动态加载的行为,以限制“全局”配置选项(如PATH)的影响。

"Lame" or not, you'll have a far more stable system if you restrict such changes to smaller scopes.

“Lame”与否,如果将此类更改限制在较小的范围内,您将拥有一个更稳定的系统。

#10


15  

Sometimes all of the previous answers simply don't work. If you want to have access to a system variable (like M2_HOME) in Eclipse or in IntelliJ IDEA the only thing that works for me in this case is:

有时,以前的所有答案都不起作用。如果您想要在Eclipse或IntelliJ IDEA中访问系统变量(如M2_HOME),在这种情况下,对我来说唯一有用的是:

First (step 1) edit /etc/launchd.conf to contain a line like this: "setenv VAR value" and then (step 2) reboot.

首先(步骤1)编辑/etc/launchd.conf以包含如下行:“setenv VAR value”然后(步骤2)重新启动。

Simply modifying .bash_profile won't work because in OS X the applications are not started as in other Unix'es; they don't inherit the parent's shell variables. All the other modifications won't work for a reason that is unknown to me. Maybe someone else can clarify about this.

简单地修改.bash_profile是行不通的,因为在OS X中应用程序不像其他Unix那样启动;它们不会继承父级的shell变量。所有其他修改都不适用于我不知道的原因。也许其他人可以澄清这一点。

#11


14  

Update (2017-08-04)

As of (at least) macOS 10.12.6 (Sierra) this method seems to have stopped working for Apache httpd (for both the system and the user option of launchctl config). Other programs do not seem to be affected. It is conceivable that this is a bug in httpd.

从(至少)macOS 10.12.6(Sierra)开始,这种方法似乎已停止为Apache httpd工作(对于launchctl config的系统和用户选项)。其他程序似乎没有受到影响。可以想象这是httpd中的一个错误。

Original answer

This concerns OS X 10.10+ (10.11+ specifically due to rootless mode where /usr/bin is no longer writeable).

这涉及OS X 10.10+(10.11+特别是由于无根模式,其中/ usr / bin不再可写)。

I've read in multiple places that using launchctl setenv PATH <new path> to set the PATH variable does not work due to a bug in OS X (which seems true from personal experience). I found that there's another way the PATH can be set for applications not launched from the shell:

我在多个地方读过,使用launchctl setenv PATH 来设置PATH变量不起作用,因为OS X中的一个错误(从个人经验来看似乎是真的)。我发现可以为未从shell启动的应用程序设置PATH的另一种方法:

sudo launchctl config user path <new path>

This option is documented in the launchctl man page:

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.

设置launchd(8)域的持久配置信息。只能配置系统域和用户域。持久存储的位置是实现细节,只应通过此子命令对该存储进行更改。通过此子命令进行的更改需要重新启动才能生效。

[...]

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.

将目标域中所有服务的PATH环境变量设置为字符串值。字符串值应符合environ(7)中PATH环境变量的轮廓格式。请注意,如果服务指定了自己的PATH,则特定于服务的环境变量将优先。

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.

注意:此工具不能用于为域中的所有服务设置常规环境变量。出于安全原因,故意将其范围限定为PATH环境变量而不是其他任何内容。

I have confirmed this to work with a GUI application started from Finder (which uses getenv to get PATH). Note that you only have to do this once and the change will be persistent through reboots.

我已经确认这可以使用从Finder启动的GUI应用程序(使用getenv来获取PATH)。请注意,您只需执行一次此操作,并且更改将在重新启动后保持不变。

#12


13  

After chasing the Environment Variables preference pane and discovering that the link is broken and a search on Apple's site seems to indicate they've forgotten about it... I started back onto the trail of the elusive launchd process.

在追逐环境变量偏好窗格并发现链接被破坏并且在Apple网站上搜索似乎表明他们已经忘记了它...我开始回到难以捉摸的启动过程的轨迹。

On my system (Mac OS X 10.6.8) it appears that variables defined in environment.plist are being reliably exported to apps launched from Spotlight (via launchd). My trouble is that those vars are not being exported to new bash sessions in Terminal. I.e. I have the opposite problem as portrayed here.

在我的系统(Mac OS X 10.6.8)上,似乎environment.plist中定义的变量可靠地导出到从Spotlight启动的应用程序(通过launchd)。我的麻烦是这些变量没有被导出到终端中的新bash会话。即我有与此处描述的相反的问题。

NOTE: environment.plist looks like JSON, not XML, as described previously

注意:environment.plist看起来像JSON,而不是XML,如前所述

I was able to get Spotlight apps to see the vars by editing ~/MacOSX/environment.plist and I was able to force the same vars into a new Terminal session by adding the following to my .profile file:

通过编辑〜/ MacOSX / environment.plist,我可以通过编辑〜/ MacOSX / environment.plist让Spotlight应用程序看到vars,并且通过将以下内容添加到我的.profile文件中,我能够将相同的vars强制进入新的终端会话:

eval $(launchctl export)

#13


10  

Any of the Bash startup files -- ~/.bashrc, ~/.bash_profile, ~/.profile. There's also some sort of weird file named ~/.MacOSX/environment.plist for environment variables in GUI applications.

任何Bash启动文件 - 〜/ .bashrc,〜/ .bash_profile,〜/ .profile。对于GUI应用程序中的环境变量,还有一些名为〜/ .MacOSX / environment.plist的奇怪文件。

#14


10  

Much like the answer Matt Curtis gave, I set environment variables via launchctl, but I wrap it in a function called export, so that whenever I export a variable like normal in my .bash_profile, it is also set by launchctl. Here is what I do:

就像Matt Curtis给出的答案一样,我通过launchctl设置环境变量,但是我将它包装在一个名为export的函数中,这样每当我在.bash_profile中导出一个像normal一样的变量时,它也会被launchctl设置。这是我做的:

  1. My .bash_profile consists solely of one line, (This is just personal preference.)

    我的.bash_profile只包含一行,(这只是个人偏好。)

    source .bashrc
    
  2. My .bashrc has this:

    我的.bashrc有这个:

    function export()
    {
        builtin export "$@"
        if [[ ${#@} -eq 1 && "${@//[^=]/}" ]]
        then
            launchctl setenv "${@%%=*}" "${@#*=}"
        elif [[ ! "${@//[^ ]/}" ]]
        then
            launchctl setenv "${@}" "${!@}"
        fi
    }
    
    export -f export
    
  3. The above will overload the Bash builtin "export" and will export everything normally (you'll notice I export "export" with it!), then properly set them for OS X app environments via launchctl, whether you use any of the following:

    以上将使Bash内置“导出”超载,并将正常导出所有内容(您会注意到我用它导出“导出”!),然后通过launchctl为OS X应用程序环境正确设置它们,无论您是否使用以下任何一项:

    export LC_CTYPE=en_US.UTF-8
    # ~$ launchctl getenv LC_CTYPE
    # en_US.UTF-8
    PATH="/usr/local/bin:${PATH}"
    PATH="/usr/local/opt/coreutils/libexec/gnubin:${PATH}"
    export PATH
    # ~$ launchctl getenv PATH
    # /usr/local/opt/coreutils/libexec/gnubin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
    export CXX_FLAGS="-mmacosx-version-min=10.9"
    # ~$ launchctl getenv CXX_FLAGS
    # -mmacosx-version-min=10.9
    
  4. This way I don't have to send every variable to launchctl every time, and I can just have my .bash_profile / .bashrc set up the way I want. Open a terminal window, check out your environment variables you're interested in with launchctl getenv myVar, change something in your .bash_profile/.bashrc, close the terminal window and re-open it, check the variable again with launchctl, and voilá, it's changed.

    这样我每次都不必将每个变量发送到launchctl,我可以按照我想要的方式设置我的.bash_profile / .bashrc。打开终端窗口,使用launchctl getenv myVar检查你感兴趣的环境变量,更改.bash_profile / .bashrc中的内容,关闭终端窗口并重新打开它,再次使用launchctl和voilá检查变量,它改变了。

  5. Again, like the other solutions for the post-Mountain Lion world, for any new environment variables to be available for apps, you need to launch or re-launch them after the change.

    同样,与后山狮世界的其他解决方案一样,对于可用于应用的任何新环境变量,您需要在更改后启动或重新启动它们。

#15


10  

Here is a very simple way to do what you want. In my case, it was getting gradle to work (for Android Studio)

这是一个非常简单的方法来做你想要的。在我的情况下,它正在获得工作(对于Android Studio)

  • Open up Terminal.
  • 打开终端。

  • Run the following command:

    运行以下命令:

    sudo nano /etc/paths or sudo vim /etc/paths

    sudo nano / etc / paths或sudo vim / etc / paths

  • Enter your password, when prompted.

    出现提示时输入您的密码。

  • Go to the bottom of the file, and enter the path you wish to add.
  • 转到文件底部,然后输入要添加的路径。

  • Hit control-x to quit.
  • 点击control-x退出。

  • Enter 'Y' to save the modified buffer.
  • 输入“Y”以保存修改后的缓冲区。

  • Open a new terminal window then type:

    打开一个新的终端窗口然后键入:

    echo $PATH

You should see the new path appended to the end of the PATH

您应该看到新路径附加到PATH的末尾

I got these details from this post:

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

http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.UkED3rxPp3Q

I hope that can help someone else

我希望能帮助别人

#16


8  

I think the OP is looking for a simple, Windows-like solution.

我认为OP正在寻找一种简单的,类似Windows的解决方案。

Here you go:

干得好:

http://www.apple.com/downloads/macosx/system_disk_utilities/environmentvariablepreferencepane.html

#17


7  

To be concise and clear about what each file is intended for

简明扼要地说明每个文件的用途

  • ~/.profile is sourced every time Terminal.app is launched
  • 每次启动Terminal.app时都会获取〜/ .profile

  • ~/.bashrc is where "traditionally" all the export statements for Bash environment are set
  • 〜/ .bashrc是“传统上”设置Bash环境的所有导出语句的地方

  • /etc/paths is the main file in Mac OS that contains the list of default paths for building the PATH environment variable for all users
  • / etc / paths是Mac OS中的主文件,其中包含用于为所有用户构建PATH环境变量的默认路径列表

  • /etc/paths.d/ contains files that hold additional search paths
  • /etc/paths.d/包含保存其他搜索路径的文件

Non-terminal programs don't inherit the system wide PATH and MANPATH variables that your terminal does! To set environment for all processes launched by a specific user, thus making environment variables available to Mac OS X GUI applications, those variables must be defined in your ~/.MacOSX/environment.plist (Apple Technical Q&A QA1067)

非终端程序不会继承终端执行的系统范围的PATH和MANPATH变量!要为特定用户启动的所有进程设置环境,从而使环境变量可用于Mac OS X GUI应用程序,必须在〜/ .MacOSX / environment.plist中定义这些变量(Apple Technical Q&A QA1067)

Use the following command line to synchronize your environment.plist with /etc/paths:

使用以下命令行将environment.plist与/ etc / paths同步:

defaults write $HOME/.MacOSX/environment PATH "$(tr '\n' ':' </etc/paths)"

#18


5  

the $PATH variable is also subject to path_helper, which in turn makes use of the /etc/paths file and files in /etc/paths.d.

$ PATH变量也受path_helper的约束,而path_helper又使用/ etc / paths文件和/etc/paths.d中的文件。

A more thorough description can be found here: http://hea-www.harvard.edu/~fine/OSX/path_helper.html

可以在这里找到更详尽的描述:http://hea-www.harvard.edu/~fine/OSX/path_helper.html

#19


3  

Setup your PATH environment variable on Mac OS

Open the Terminal program (this is in your Applications/Utilites folder by default). Run the following command touch ~/.bash_profile; open ~/.bash_profile This will open the file in the your default text editor.

打开终端程序(默认位于Applications / Utilites文件夹中)。执行以下命令touch~ / .bash_profile; open~ / .bash_profile这将在您的默认文本编辑器中打开该文件。

For ANDROID SDK as example :

以ANDROID SDK为例:

You need to add the path to your Android SDK platform-tools and tools directory. In my example I will use "/Development/android-sdk-macosx" as the directory the SDK is installed in. Add the following line:

您需要添加Android SDK平台工具和工具目录的路径。在我的示例中,我将使用“/ Development / android-sdk-macosx”作为安装SDK的目录。添加以下行:

export PATH=${PATH}:/Development/android-sdk-macosx/platform-tools:/Development/android-sdk-macosx/tools

Save the file and quit the text editor. Execute your .bash_profile to update your PATH.

保存文件并退出文本编辑器。执行.bash_profile以更新PATH。

source ~/.bash_profile

Now everytime you open the Terminal program you PATH will included the Android SDK.

现在每次打开终端程序时,PATH都会包含Android SDK。

#20


3  

It's simple:

Edit ~/.profile and put your variables as follow

编辑〜/ .profile并将变量放在下面

$ vim ~/.profile

$ vim~ / .profile

In file put:

在文件中:

MY_ENV_VAR=value

  1. Save ( :wq )

    保存(:wq)

  2. Restart the terminal (Quit and open it again)

    重启终端(退出并再次打开)

  3. Make sure that`s all be fine:

    确保一切都很好:

$ echo $MY_ENV_VAR

$ echo $ MY_ENV_VAR

$ value


#21


3  

/etc/launchd.conf is not used in Yosemite, El Capitain, or (High) Sierra

From the launchctl man page:

从launchctl手册页:

/etc/launchd.conf file is no longer consulted for subcommands to run during early boot time;
this functionality was removed for security considerations.

The method described in this Ask Different answer works for me (after a reboot): applications launched from the Dock or from Spotlight inherit environment variables that I set in ~/Library/LaunchAgents/my.startup.plist. (In my case, I needed to set LANG, to en_US.UTF-8, for a Sublime Text plugin.)

此Ask Ask中描述的方法适用于我(重启后):从Dock或Spotlight启动的应用程序继承了我在〜/ Library / LaunchAgents / my.startup.plist中设置的环境变量。 (就我而言,我需要将LANG设置为en_US.UTF-8,用于Sublime Text插件。)

#22


3  

For a single user modification, use ~/.profile of the ones you listed. The following link explains when the different files are read by Bash.

对于单个用户修改,请使用您列出的〜/ .profile。以下链接说明了Bash读取不同文件的时间。

http://telin.ugent.be/~slippens/drupal/bashrc_and_others

If you want to set the environment variable for gui applications you need the ~/.MacOSX/environment.plist file

如果要为gui应用程序设置环境变量,则需要〜/ .MacOSX / environment.plist文件

#23


3  

Well, I'm unsure about the /etc/paths and ~/.MacOSX/environment.plist files. Those are new.

好吧,我不确定/ etc / paths和〜/ .MacOSX / environment.plist文件。那是新的。

But with Bash, you should know that .bashrc is executed with every new shell invocation and .bash_profile is only executed once at startup.

但是对于Bash,你应该知道.bashrc是在每次新的shell调用时执行的.bash_profile只在启动时执行一次。

I don't know how often this is with Mac OS X. I think the distinction has broken down with the window system launching everything.

我不知道Mac OS X的频率是多少。我认为这种区别已经打破了窗口系统启动一切。

Personally, I eliminate the confusion by creating a .bashrc file with everything I need and then do:

就个人而言,我通过创建一个包含我需要的所有内容的.bashrc文件来消除混淆,然后执行:

ln -s .bashrc .bash_profile

#24


2  

There are two type of shells at play here.

这里有两种类型的贝壳。

  • Non-Login: .bashrc is reloaded every time you start a new copy of bash
  • 非登录:每次启动bash的新副本时都会重新加载.bashrc

  • Login: The .profile is loaded only when you either login, or explicitly tell bash to load it and use it as a login shell.
  • 登录:.profile仅在您登录时加载,或者明确告诉bash加载它并将其用作登录shell。

Its important to understand here that with bash .bashrc is only read by a shell that's both interactive and non-login, and you will find that people often load .bashrc in .bash_profile to overcome this limitation.

重要的是要理解,使用bash .bashrc只能由一个既可以进行交互也可以进行非登录的shell读取,你会发现人们经常在.bash_profile中加载.bashrc来克服这个限制。

Now that you have the basic understanding, lets move on to how i would advice you to set it up.

既然您已经掌握了基本知识,那么我们将继续讨论如何建议您进行设置。

  • .profile: create it non-existing. Put your PATH setup in there.
  • .profile:创建它不存在。将PATH设置放在那里。

  • .bashrc: create if non-existing. Put all your Aliases and Custom method in there.
  • .bashrc:如果不存在则创建。将所有别名和自定义方法放在那里。

  • .bash_profile: create if non-existing. Put the following in there.
  • .bash_profile:如果不存在则创建。把以下内容放在那里。

.bash_file:

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

#25


2  

Login Shells

/etc/profile

The shell first executes the commands in /etc/profile. A user working with root privileges can set up this file to establish systemwide default characteristics for users running bash.

shell首先执行/ etc / profile中的命令。使用root权限的用户可以设置此文件,以便为运行bash的用户建立系统范围的默认特征。

.bash_profile 
.bash_login 
.profile

Next the shell looks for ~/.bash_profile, ~/.bash_login, and ~/.profile (~/ is short- hand for your home directory), in that order, executing the commands in the first of these files it finds. You can put commands in one of these files to override the defaults set in /etc/profile. A shell running on a virtual terminal does not execute commands in these files.

接下来,shell按顺序查找〜/ .bash_profile,〜/ .bash_login和〜/ .profile(〜/是您的主目录的简写),执行它找到的第一个文件中的命令。您可以将命令放在其中一个文件中,以覆盖/ etc / profile中设置的默认值。在虚拟终端上运行的shell不会在这些文件中执行命令。

.bash_logout

When you log out, bash executes commands in the ~/.bash_logout file. This file often holds commands that clean up after a session, such as those that remove temporary files.

当您注销时,bash会执行〜/ .bash_logout文件中的命令。此文件通常包含在会话后清理的命令,例如删除临时文件的命令。

Interactive Nonlogin Shells

交互式非登录外壳

/etc/bashrc

Although not called by bash directly, many ~/.bashrc files call /etc/bashrc. This setup allows a user working with root privileges to establish systemwide default characteristics for nonlogin bash shells.

虽然没有直接调用bash,但很多〜/ .bashrc文件调用/ etc / bashrc。此设置允许使用root权限的用户为非登录bash shell建立系统范围的默认特征。

.bashrc

An interactive nonlogin shell executes commands in the ~/.bashrc file. Typically a startup file for a login shell, such as .bash_profile, runs this file, so both login and nonlogin shells run the commands in .bashrc.

交互式非登录shell在〜/ .bashrc文件中执行命令。通常,登录shell的启动文件(例如.bash_profile)运行此文件,因此login和nonlogin shell都运行.bashrc中的命令。

Because commands in .bashrc may be executed many times, and because subshells inherit exported variables, it is a good idea to put commands that add to existing variables in the .bash_profile file.

因为.bashrc中的命令可能会执行多次,并且因为子shell继承了导出的变量,所以最好将添加到.bash_profile文件中的现有变量的命令。

#26


2  

One thing to note in addition to the approaches suggested is that, in OS X 10.5 (Leopard) at least, the variables set in launchd.conf will be merged with the settings made in .profile. I suppose this is likely to be valid for the settings in ~/.MacOSX/environment.plist too, but I haven't verified.

除了建议的方法之外,还有一点需要注意的是,至少在OS X 10.5(Leopard)中,launchd.conf中设置的变量将与.profile中的设置合并。我想这也可能对〜/ .MacOSX / environment.plist中的设置有效,但我还没有验证。

#27


1  

For Bash, try adding your environment variables to the file /etc/profile to make them available for all users. No need to reboot, just start a new Terminal session.

对于Bash,请尝试将环境变量添加到文件/ etc / profile中,以使其可供所有用户使用。无需重启,只需启动新的终端会话即可。

#28


1  

It's quite simple, edit .profile (vi, nano, sublimeText or other text editor) file, you can found it at ~/ directory (user directory) and set like this :

这很简单,编辑.profile(vi,nano,sublimeText或其他文本编辑器)文件,你可以在〜/ directory(用户目录)找到它并设置如下:

export MY_VAR=[your value here]

导出MY_VAR = [你的价值在这里]

exemple with java home :

例如java home:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/current

save it and return to the terminal.

保存并返回终端。

You can reload it with :

您可以使用以下命令重新加载:

source .profileor close / open your terminal window.

source .profileor关闭/打开您的终端窗口。

#29


1  

Just did this really easy and quick. First create a ~/.bash_profile from terminal:

这样做非常简单快捷。首先从终端创建一个〜/ .bash_profile:

touch .bash_profile

then

open -a TextEdit.app .bash_profile

add

export TOMCAT_HOME=/Library/Tomcat/Home

save documement and you are done.

保存文件,你就完成了。

#30


1  

All the Magic on IOS only goes with using source with the file, where you export your ENV-Variables.

IOS上的所有Magic都只使用source和文件,在那里导出ENV-Variables。

For Example:

You can create an File like this:

您可以像这样创建一个文件:

export bim=fooo
export bom=bar

Save this file as bimbom.env , and do source ./bimbom.ev Voilá, you got your ENV-Variables.

将此文件保存为bimbom.env,并执行./bimbom.evVoilá,您获得了ENV-Variables。

Check them with: echo $bim

检查它们:echo $ bim

#1


618  

Bruno is right on track. I've done extensive research and if you want to set variables that are available in all GUI applications, your only option is /etc/launchd.conf.

布鲁诺正好走上正轨。我做了大量的研究,如果你想设置所有GUI应用程序中可用的变量,你唯一的选择是/etc/launchd.conf。

Please note that environment.plist does not work for applications launched via Spotlight. This is documented by Steve Sexton here.

请注意,environment.plist不适用于通过Spotlight启动的应用程序。史蒂夫塞克斯顿在这里记录了这一点。

  1. Open a terminal prompt

    打开终端提示

  2. Type sudo vi /etc/launchd.conf (note: this file might not yet exist)

    输入sudo vi /etc/launchd.conf(注意:此文件可能尚不存在)

  3. Put contents like the following into the file

    将以下内容放入文件中

    # Set environment variables here so they are available globally to all apps
    # (and Terminal), including those launched via Spotlight.
    #
    # After editing this file run the following command from the terminal to update
    # environment variables globally without needing to reboot.
    # NOTE: You will still need to restart the relevant application (including
    # Terminal) to pick up the changes!
    # grep -E "^setenv" /etc/launchd.conf | xargs -t -L 1 launchctl
    #
    # See http://www.digitaledgesw.com/node/31
    # and http://*.com/questions/135688/setting-environment-variables-in-os-x/
    #
    # Note that you must hardcode the paths below, don't use environment variables.
    # You also need to surround multiple values in quotes, see MAVEN_OPTS example below.
    #
    setenv JAVA_VERSION 1.6
    setenv JAVA_HOME /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
    setenv GROOVY_HOME /Applications/Dev/groovy
    setenv GRAILS_HOME /Applications/Dev/grails
    setenv NEXUS_HOME /Applications/Dev/nexus/nexus-webapp
    setenv JRUBY_HOME /Applications/Dev/jruby
    
    setenv ANT_HOME /Applications/Dev/apache-ant
    setenv ANT_OPTS -Xmx512M
    
    setenv MAVEN_OPTS "-Xmx1024M -XX:MaxPermSize=512m"
    setenv M2_HOME /Applications/Dev/apache-maven
    
    setenv JMETER_HOME /Applications/Dev/jakarta-jmeter
    
  4. Save your changes in vi and reboot your Mac. Or use the grep/xargs command which is shown in the code comment above.

    在vi中保存更改并重新启动Mac。或者使用上面代码注释中显示的grep / xargs命令。

  5. Prove that your variables are working by opening a Terminal window and typing export and you should see your new variables. These will also be available in IntelliJ IDEA and other GUI applications you launch via Spotlight.

    通过打开终端窗口并键入export来证明您的变量正常工作,您应该看到新的变量。这些也可以在您通过Spotlight启动的IntelliJ IDEA和其他GUI应用程序中使用。

#2


245  

How to set the environment for new processes started by Spotlight (without needing to reboot)

You can set the environment used by launchd (and, by extension, anything started from Spotlight) with launchctl setenv. For example to set the path:

您可以使用launchctl setenv设置launchd(以及扩展名,从Spotlight启动的任何内容)使用的环境。例如,设置路径:

launchctl setenv PATH /opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin

Or if you want to set up your path in .bashrc or similar, then have it mirrored in launchd:

或者,如果要在.bashrc或类似路径中设置路径,请将其镜像到launchd中:

PATH=/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin
launchctl setenv PATH $PATH

There's no need to reboot though you will need to restart an app if you want it to pick up the changed environment.

没有必要重新启动,但如果您希望它能够获取更改的环境,则需要重新启动应用程序。

This includes any shells already running under Terminal.app, although if you're there you can set the environment more directly, e.g. with export PATH=/opt/local/bin:/opt/local/sbin:$PATH for bash or zsh.

这包括已经在Terminal.app下运行的所有shell,但如果你在那里,你可以更直接地设置环境,例如with export PATH = / opt / local / bin:/ opt / local / sbin:$ PATH for bash或zsh。

How to keeping changes after a reboot

To keep changes after a reboot you can set the environment variables from /etc/launchd.conf, like so:

要在重新启动后保持更改,可以在/etc/launchd.conf中设置环境变量,如下所示:

setenv PATH /opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin

launchd.conf is executed automatically when you reboot.

重启时会自动执行launchd.conf。

If you want these changes to take effect now, you should use this command to reprocess launchctl.conf (thanks @mklement for the tip!)

如果您希望这些更改现在生效,您应该使用此命令重新处理launchctl.conf(感谢@mklement提示!)

egrep -v '^\s*#' /etc/launchd.conf | launchctl

You can find out more about launchctl and how it loads launchd.conf with the command man launchctl.

您可以使用命令man launchctl找到有关launchctl及其如何加载launchd.conf的更多信息。

#3


104  

Up to and including OS X v10.7 (Lion) you can set them in:

在OS X v10.7(Lion)中,您可以将它们设置为:

~/.MacOSX/environment.plist

See:

For PATH in the Terminal, you should be able to set in .bash_profile or .profile (you'll probably have to create it though)

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

For OS X v10.8 (Mountain Lion) and beyond you need to use launchd and launchctl.

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

#4


56  

Solution for both command line and GUI apps from a single source (works with Yosemite & El Capitan)

Let's assume you have environment variable definitions in your ~/.bash_profile like in the following snippet:

假设您在〜/ .bash_profile中有环境变量定义,如下面的代码片段所示:

export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"
export GOPATH="$HOME/go"
export PATH="$PATH:/usr/local/opt/go/libexec/bin:$GOPATH/bin"
export PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
export MANPATH="/usr/local/opt/coreutils/libexec/gnuman:$MANPATH"

We need a Launch Agent which will run on each login and anytime on demand which is going to load these variables to the user session. We'll also need a shell script to parse these definitions and build necessary commands to be executed by the agent.

我们需要一个启动代理,它将在每次登录时随时随地运行,并将这些变量加载到用户会话。我们还需要一个shell脚本来解析这些定义并构建由代理执行的必要命令。

Create a file with plist suffix (e.g. named osx-env-sync.plist) in ~/Library/LaunchAgents/ directory with the following contents:

在〜/ Library / LaunchAgents /目录中创建一个带有plist后缀的文件(例如命名为osx-env-sync.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>osx-env-sync</string>
  <key>ProgramArguments</key>
  <array>
    <string>bash</string>
    <string>-l</string>
    <string>-c</string>
    <string>
      $HOME/.osx-env-sync.sh
    </string>
  </array>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>

-l parameter is critical here; it's necessary for executing the shell script with a login shell so that ~/.bash_profile is sourced in the first place before this script is executed.

-l参数在这里至关重要;使用登录shell执行shell脚本是必要的,以便在执行此脚本之前首先获取〜/ .bash_profile。

Now, the shell script. Create it at ~/.osx-env-sync.sh with the following contents:

现在,shell脚本。使用以下内容在〜/ .osx-env-sync.sh创建它:

grep export $HOME/.bash_profile | while IFS=' =' read ignoreexport envvar ignorevalue; do
  launchctl setenv ${envvar} ${!envvar}
done

Make sure the shell script is executable:

确保shell脚本是可执行的:

chmod +x ~/.osx-env-sync.sh

Now, load the launch agent for current session:

现在,加载当前会话的启动代理:

launchctl load ~/Library/LaunchAgents/osx-env-sync.plist

(Re)Launch a GUI application and verify that it can read the environment variables.

(重新)启动GUI应用程序并验证它是否可以读取环境变量。

The setup is persistent. It will survive restarts and relogins.

设置是持久的。它将在重新启动和重新运行后继续存在。

After the initial setup (that you just did), if you want to reflect any changes in your ~/.bash_profile to your whole environment again, rerunning the launchctl load ... command won't perform what you want; instead you'll get a warning like the following:

在初始设置之后(您刚刚进行了设置),如果您希望将〜/ .bash_profile中的任何更改再次反映到整个环境中,则重新运行launchctl load ...命令将无法执行您想要的操作;相反,你会收到如下警告:

<$HOME>/Library/LaunchAgents/osx-env-sync.plist: Operation already in progress

<$ HOME> /Library/LaunchAgents/osx-env-sync.plist:操作已在进行中

In order to reload your environment variables without going through the logout/login process do the following:

要在不经过注销/登录过程的情况下重新加载环境变量,请执行以下操作:

launchctl unload ~/Library/LaunchAgents/osx-env-sync.plist
launchctl load ~/Library/LaunchAgents/osx-env-sync.plist

Finally make sure that you relaunch your already running applications (including Terminal.app) to make them aware of the changes.

最后确保重新启动已经运行的应用程序(包括Terminal.app),以使他们了解更改。

I've also pushed the code and explanations here to a GitHub project: osx-env-sync.

我还将代码和解释推送到GitHub项目:osx-env-sync。

I hope this is going to be the ultimate solution, at least for the latest versions of OS X (Yosemite & El Capitan).

我希望这将是最终解决方案,至少对于最新版本的OS X(Yosemite和El Capitan)而言。

#5


47  

1.

vim ~/.bash_profile

The file may not exist (if not, you can just create it).

该文件可能不存在(如果没有,您可以创建它)。

2.type in this and save the file:

2.在此输入并保存文件:

export PATH=$PATH:YOUR_PATH_HERE

3.run

source ~/.bash_profile

#6


35  

There are essentially two problems to solve when dealing with environment variables in OS X. The first is when invoking programs from Spotlight (the magnifying glass icon on the right side of the Mac menu/status bar) and the second when invoking programs from the Dock. Invoking programs from a Terminal application/utility is trivial because it reads the environment from the standard shell locations (~/.profile, ~/.bash_profile, ~/.bashrc, etc.)

在OS X中处理环境变量时,基本上有两个问题需要解决。第一个是从Spotlight调用程序(Mac菜单/状态栏右侧的放大镜图标),第二个是从Dock调用程序时。从终端应用程序/实用程序调用程序是微不足道的,因为它从标准shell位置读取环境(〜/ .profile,〜/ .bash_profile,〜/ .bashrc等)

When invoking programs from the Dock, use ~/.MacOSX/environment.plist where the <dict> element contains a sequence of <key>KEY</key><string>theValue</string> elements.

从Dock调用程序时,使用〜/ .MacOSX / environment.plist,其中<​​dict>元素包含 KEY theValue 元素的序列。

When invoking programs from Spotlight, ensure that launchd has been setup with all the key/value settings you require.

从Spotlight调用程序时,请确保已使用所需的所有键/值设置设置launchd。

To solve both problems simultaneously, I use a login item (set via the System Preferences tool) on my User account. The login item is a bash script that invokes an Emacs lisp function although one can of course use their favorite scripting tool to accomplish the same thing. This approach has the added benefit that it works at any time and does not require a reboot, i.e. one can edit ~/.profile, run the login item in some shell and have the changes visible for newly invoked programs, from either the Dock or Spotlight.

要同时解决这两个问题,我在用户帐户上使用登录项(通过“系统首选项”工具设置)。登录项是一个调用Emacs lisp函数的bash脚本,尽管当然可以使用他们喜欢的脚本工具来完成同样的事情。这种方法有额外的好处,它可以在任何时候工作,不需要重新启动,即可以编辑〜/ .profile,在某些shell中运行登录项,并对Dock中的新调用的程序进行更改。聚光灯。

Details:

Login item: ~/bin/macosx-startup

登录项目:〜/ bin / macosx-startup

#!/bin/bash
bash -l -c "/Applications/Emacs.app/Contents/MacOS/Emacs --batch -l ~/lib/emacs/elisp/macosx/environment-support.el -f generate-environment"

Emacs lisp function: ~/lib/emacs/elisp/macosx/envionment-support.el

Emacs lisp函数:〜/ lib / emacs / elisp / macosx / envionment-support.el

;;; Provide support for the environment on Mac OS X

(defun generate-environment ()
  "Dump the current environment into the ~/.MacOSX/environment.plist file."
  ;; The system environment is found in the global variable:
  ;; 'initial-environment' as a list of "KEY=VALUE" pairs.
  (let ((list initial-environment)
        pair start command key value)
    ;; clear out the current environment settings
    (find-file "~/.MacOSX/environment.plist")
    (goto-char (point-min))
    (setq start (search-forward "<dict>\n"))
    (search-forward "</dict>")
    (beginning-of-line)
    (delete-region start (point))
    (while list
      (setq pair (split-string (car list) "=")
            list (cdr list))
      (setq key (nth 0 pair)
            value (nth 1 pair))
      (insert "  <key>" key "</key>\n")
      (insert "  <string>" value "</string>\n")

      ;; Enable this variable in launchd
      (setq command (format "launchctl setenv %s \"%s\"" key value))
      (shell-command command))
    ;; Save the buffer.
    (save-buffer)))

NOTE: This solution is an amalgam of those coming before I added mine, particularly that offered by Matt Curtis, but I have deliberately tried to keep my ~/.bash_profile content platform independent and put the setting of the launchd environment (a Mac only facility) into a separate script.

注意:这个解决方案是我加入我的之前的混合物,特别是Matt Curtis提供的那些,但我故意试图保持我的〜/ .bash_profile内容平*立并放置启动环境的设置(仅限Mac设施) )进入一个单独的脚本。

#7


21  

Another, free, opensource, Mac OSX Mountain Lion (10.8) Preference pane/environment.plist solution is EnvPane.

另一个免费的开源Mac OSX Mountain Lion(10.8)Preference pane / environment.plist解决方案是EnvPane。

EnvPane's source code available on Github. EnvPane looks like it has comparable features to RCEnvironment, however, it seems it can update its stored variables instantly, i.e. without the need for a restart or login, which is welcome.

EnvPane的源代码可在Github上获得。 EnvPane看起来具有与RCEnvironment类似的功能,但是,它似乎可以立即更新其存储的变量,即无需重启或登录,这是受欢迎的。

As stated by the developer:

正如开发人员所说:

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.

EnvPane是Mac OS X 10.8(Mountain Lion)的首选项窗格,可让您为图形和终端会话中的所有程序设置环境变量。它不仅可以恢复对Mountain Lion中〜/ .MacOSX / environment.plist的支持,还可以立即发布您对环境的更改,而无需注销并重新登录。 EnvPane包括(并自动安装)在登录后早期运行1)的launchd代理和2)每当〜/ .MacOSX / environment.plist发生更改时。代理读取〜/ .MacOSX / environment.plist,并通过launchctl setenv和launchctl unsetenv使用的相同API将该文件中的环境变量导出到当前用户的launchd实例。

Disclaimer: I am in no way related to the developer or his/her project.

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

P.S. I like the name (sounds like 'Ends Pain').

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

#8


17  

On Mountain Lion all the /etc/paths and /etc/launchd.conf editing doesn't take any effect!

在Mountain Lion上,所有/ etc / paths和/etc/launchd.conf编辑都没有任何效果!

Apple's Developer Forums say:

Apple的开发者论坛说:

"Change the Info.plist of the .app itself to contain an "LSEnvironment" dictionary with the environment variables you want.

“更改.app本身的Info.plist以包含带有所需环境变量的”LSEnvironment“字典。

~/.MacOSX/environment.plist is no longer supported."

不再支持〜/ .MacOSX / environment.plist。“

So I directly edited the app's Info.plist (right click on "AppName.app" (in this case SourceTree) and then "Show package contents")

所以我直接编辑了应用程序的Info.plist(右键单击“AppName.app”(在本例中为SourceTree),然后“显示包内容”)

在OS X上设置环境变量

and added a new key/dict pair called:

并添加了一个名为的新键/ dict对:

<key>LSEnvironment</key>
<dict>
     <key>PATH</key>
     <string>/Users/flori/.rvm/gems/ruby-1.9.3-p362/bin:/Users/flori/.rvm/gems/ruby-1.9.3-p362@global/bin:/Users/flori/.rvm/rubies/ruby-1.9.3-p326/bin:/Users/flori/.rvm/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:</string>
</dict>

(see: LaunchServicesKeys Documentation at Apple)

(请参阅:Apple的LaunchServicesKeys文档)

在OS X上设置环境变量

now the App (in my case SourceTree) uses the given path and works with git 1.9.3 :-)

现在App(在我的情况下是SourceTree)使用给定的路径并使用git 1.9.3 :-)

PS: Of course you have to adjust the Path entry to your specific path needs.

PS:当然,您必须根据特定路径需求调整Path条目。

#9


16  

While the answers here aren't "wrong", I'll add another: never make environment variable changes in OS X that affect "all processes", or even, outside the shell, for all processes run interactively by a given user.

虽然这里的答案并非“错误”,但我将添加另一个:永远不要在OS X中对环境变量进行更改,这些更改会影响“所有进程”,甚至在shell外部,对于给定用户以交互方式运行的所有进程。

In my experience, global changes to environment variables like PATH for all processes are even more likely to break things on OS X than on Windows. Reason being, lots of OS X applications and other software (including, perhaps especially, components of the OS itself) rely on UNIX command-line tools under the hood, and assume the behavior of the versions of these tools provided with the system, and don't necessarily use absolute paths when doing so (similar comments apply to dynamically-loaded libraries and DYLD_* environment variables). Consider, for instance, that the highest-rated answers to various Stack Overflow questions about replacing OS X-supplied versions of interpreters like Python and Ruby generally say "don't do this."

根据我的经验,对于所有进程的环境变量(如PATH)的全局更改甚至更可能破坏OS X而不是Windows。原因是,许多OS X应用程序和其他软件(包括,特别是OS本身的组件)依赖于UNIX命令行工具,并假设系统提供的这些工具的版本行为,以及这样做时不一定使用绝对路径(类似的注释适用于动态加载的库和DYLD_ *环境变量)。例如,考虑一下有关替换OS X提供的解释器版本(如Python和Ruby)的各种Stack Overflow问题的最高评级答案通常会说“不要这样做”。

OS X is really no different than other UNIX-like operating systems (e.g., Linux, FreeBSD, and Solaris) in this respect; the most likely reason Apple doesn't provide an easy way to do this is because it breaks things. To the extent Windows isn't as prone to these problems, it's due to two things: (1) Windows software doesn't tend to rely on command-line tools to the extent that UNIX software does, and (2) Microsoft has had such an extensive history of both "DLL hell" and security problems caused by changes that affect all processes that they've changed the behavior of dynamic loading in newer Windows versions to limit the impact of "global" configuration options like PATH.

在这方面,OS X与其他类UNIX操作系统(例如Linux,FreeBSD和Solaris)没有什么不同;苹果公司没有提供简单方法的最可能原因是因为它打破了局面。在某种程度上,Windows并不容易出现这些问题,这主要归功于两件事:(1)Windows软件不像UNIX软件那样依赖命令行工具,(2)微软已经拥有“DLL地狱”这样一个广泛的历史记录和由影响所有进程的更改引起的安全问题,它们改变了新版Windows动态加载的行为,以限制“全局”配置选项(如PATH)的影响。

"Lame" or not, you'll have a far more stable system if you restrict such changes to smaller scopes.

“Lame”与否,如果将此类更改限制在较小的范围内,您将拥有一个更稳定的系统。

#10


15  

Sometimes all of the previous answers simply don't work. If you want to have access to a system variable (like M2_HOME) in Eclipse or in IntelliJ IDEA the only thing that works for me in this case is:

有时,以前的所有答案都不起作用。如果您想要在Eclipse或IntelliJ IDEA中访问系统变量(如M2_HOME),在这种情况下,对我来说唯一有用的是:

First (step 1) edit /etc/launchd.conf to contain a line like this: "setenv VAR value" and then (step 2) reboot.

首先(步骤1)编辑/etc/launchd.conf以包含如下行:“setenv VAR value”然后(步骤2)重新启动。

Simply modifying .bash_profile won't work because in OS X the applications are not started as in other Unix'es; they don't inherit the parent's shell variables. All the other modifications won't work for a reason that is unknown to me. Maybe someone else can clarify about this.

简单地修改.bash_profile是行不通的,因为在OS X中应用程序不像其他Unix那样启动;它们不会继承父级的shell变量。所有其他修改都不适用于我不知道的原因。也许其他人可以澄清这一点。

#11


14  

Update (2017-08-04)

As of (at least) macOS 10.12.6 (Sierra) this method seems to have stopped working for Apache httpd (for both the system and the user option of launchctl config). Other programs do not seem to be affected. It is conceivable that this is a bug in httpd.

从(至少)macOS 10.12.6(Sierra)开始,这种方法似乎已停止为Apache httpd工作(对于launchctl config的系统和用户选项)。其他程序似乎没有受到影响。可以想象这是httpd中的一个错误。

Original answer

This concerns OS X 10.10+ (10.11+ specifically due to rootless mode where /usr/bin is no longer writeable).

这涉及OS X 10.10+(10.11+特别是由于无根模式,其中/ usr / bin不再可写)。

I've read in multiple places that using launchctl setenv PATH <new path> to set the PATH variable does not work due to a bug in OS X (which seems true from personal experience). I found that there's another way the PATH can be set for applications not launched from the shell:

我在多个地方读过,使用launchctl setenv PATH 来设置PATH变量不起作用,因为OS X中的一个错误(从个人经验来看似乎是真的)。我发现可以为未从shell启动的应用程序设置PATH的另一种方法:

sudo launchctl config user path <new path>

This option is documented in the launchctl man page:

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.

设置launchd(8)域的持久配置信息。只能配置系统域和用户域。持久存储的位置是实现细节,只应通过此子命令对该存储进行更改。通过此子命令进行的更改需要重新启动才能生效。

[...]

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.

将目标域中所有服务的PATH环境变量设置为字符串值。字符串值应符合environ(7)中PATH环境变量的轮廓格式。请注意,如果服务指定了自己的PATH,则特定于服务的环境变量将优先。

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.

注意:此工具不能用于为域中的所有服务设置常规环境变量。出于安全原因,故意将其范围限定为PATH环境变量而不是其他任何内容。

I have confirmed this to work with a GUI application started from Finder (which uses getenv to get PATH). Note that you only have to do this once and the change will be persistent through reboots.

我已经确认这可以使用从Finder启动的GUI应用程序(使用getenv来获取PATH)。请注意,您只需执行一次此操作,并且更改将在重新启动后保持不变。

#12


13  

After chasing the Environment Variables preference pane and discovering that the link is broken and a search on Apple's site seems to indicate they've forgotten about it... I started back onto the trail of the elusive launchd process.

在追逐环境变量偏好窗格并发现链接被破坏并且在Apple网站上搜索似乎表明他们已经忘记了它...我开始回到难以捉摸的启动过程的轨迹。

On my system (Mac OS X 10.6.8) it appears that variables defined in environment.plist are being reliably exported to apps launched from Spotlight (via launchd). My trouble is that those vars are not being exported to new bash sessions in Terminal. I.e. I have the opposite problem as portrayed here.

在我的系统(Mac OS X 10.6.8)上,似乎environment.plist中定义的变量可靠地导出到从Spotlight启动的应用程序(通过launchd)。我的麻烦是这些变量没有被导出到终端中的新bash会话。即我有与此处描述的相反的问题。

NOTE: environment.plist looks like JSON, not XML, as described previously

注意:environment.plist看起来像JSON,而不是XML,如前所述

I was able to get Spotlight apps to see the vars by editing ~/MacOSX/environment.plist and I was able to force the same vars into a new Terminal session by adding the following to my .profile file:

通过编辑〜/ MacOSX / environment.plist,我可以通过编辑〜/ MacOSX / environment.plist让Spotlight应用程序看到vars,并且通过将以下内容添加到我的.profile文件中,我能够将相同的vars强制进入新的终端会话:

eval $(launchctl export)

#13


10  

Any of the Bash startup files -- ~/.bashrc, ~/.bash_profile, ~/.profile. There's also some sort of weird file named ~/.MacOSX/environment.plist for environment variables in GUI applications.

任何Bash启动文件 - 〜/ .bashrc,〜/ .bash_profile,〜/ .profile。对于GUI应用程序中的环境变量,还有一些名为〜/ .MacOSX / environment.plist的奇怪文件。

#14


10  

Much like the answer Matt Curtis gave, I set environment variables via launchctl, but I wrap it in a function called export, so that whenever I export a variable like normal in my .bash_profile, it is also set by launchctl. Here is what I do:

就像Matt Curtis给出的答案一样,我通过launchctl设置环境变量,但是我将它包装在一个名为export的函数中,这样每当我在.bash_profile中导出一个像normal一样的变量时,它也会被launchctl设置。这是我做的:

  1. My .bash_profile consists solely of one line, (This is just personal preference.)

    我的.bash_profile只包含一行,(这只是个人偏好。)

    source .bashrc
    
  2. My .bashrc has this:

    我的.bashrc有这个:

    function export()
    {
        builtin export "$@"
        if [[ ${#@} -eq 1 && "${@//[^=]/}" ]]
        then
            launchctl setenv "${@%%=*}" "${@#*=}"
        elif [[ ! "${@//[^ ]/}" ]]
        then
            launchctl setenv "${@}" "${!@}"
        fi
    }
    
    export -f export
    
  3. The above will overload the Bash builtin "export" and will export everything normally (you'll notice I export "export" with it!), then properly set them for OS X app environments via launchctl, whether you use any of the following:

    以上将使Bash内置“导出”超载,并将正常导出所有内容(您会注意到我用它导出“导出”!),然后通过launchctl为OS X应用程序环境正确设置它们,无论您是否使用以下任何一项:

    export LC_CTYPE=en_US.UTF-8
    # ~$ launchctl getenv LC_CTYPE
    # en_US.UTF-8
    PATH="/usr/local/bin:${PATH}"
    PATH="/usr/local/opt/coreutils/libexec/gnubin:${PATH}"
    export PATH
    # ~$ launchctl getenv PATH
    # /usr/local/opt/coreutils/libexec/gnubin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
    export CXX_FLAGS="-mmacosx-version-min=10.9"
    # ~$ launchctl getenv CXX_FLAGS
    # -mmacosx-version-min=10.9
    
  4. This way I don't have to send every variable to launchctl every time, and I can just have my .bash_profile / .bashrc set up the way I want. Open a terminal window, check out your environment variables you're interested in with launchctl getenv myVar, change something in your .bash_profile/.bashrc, close the terminal window and re-open it, check the variable again with launchctl, and voilá, it's changed.

    这样我每次都不必将每个变量发送到launchctl,我可以按照我想要的方式设置我的.bash_profile / .bashrc。打开终端窗口,使用launchctl getenv myVar检查你感兴趣的环境变量,更改.bash_profile / .bashrc中的内容,关闭终端窗口并重新打开它,再次使用launchctl和voilá检查变量,它改变了。

  5. Again, like the other solutions for the post-Mountain Lion world, for any new environment variables to be available for apps, you need to launch or re-launch them after the change.

    同样,与后山狮世界的其他解决方案一样,对于可用于应用的任何新环境变量,您需要在更改后启动或重新启动它们。

#15


10  

Here is a very simple way to do what you want. In my case, it was getting gradle to work (for Android Studio)

这是一个非常简单的方法来做你想要的。在我的情况下,它正在获得工作(对于Android Studio)

  • Open up Terminal.
  • 打开终端。

  • Run the following command:

    运行以下命令:

    sudo nano /etc/paths or sudo vim /etc/paths

    sudo nano / etc / paths或sudo vim / etc / paths

  • Enter your password, when prompted.

    出现提示时输入您的密码。

  • Go to the bottom of the file, and enter the path you wish to add.
  • 转到文件底部,然后输入要添加的路径。

  • Hit control-x to quit.
  • 点击control-x退出。

  • Enter 'Y' to save the modified buffer.
  • 输入“Y”以保存修改后的缓冲区。

  • Open a new terminal window then type:

    打开一个新的终端窗口然后键入:

    echo $PATH

You should see the new path appended to the end of the PATH

您应该看到新路径附加到PATH的末尾

I got these details from this post:

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

http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.UkED3rxPp3Q

I hope that can help someone else

我希望能帮助别人

#16


8  

I think the OP is looking for a simple, Windows-like solution.

我认为OP正在寻找一种简单的,类似Windows的解决方案。

Here you go:

干得好:

http://www.apple.com/downloads/macosx/system_disk_utilities/environmentvariablepreferencepane.html

#17


7  

To be concise and clear about what each file is intended for

简明扼要地说明每个文件的用途

  • ~/.profile is sourced every time Terminal.app is launched
  • 每次启动Terminal.app时都会获取〜/ .profile

  • ~/.bashrc is where "traditionally" all the export statements for Bash environment are set
  • 〜/ .bashrc是“传统上”设置Bash环境的所有导出语句的地方

  • /etc/paths is the main file in Mac OS that contains the list of default paths for building the PATH environment variable for all users
  • / etc / paths是Mac OS中的主文件,其中包含用于为所有用户构建PATH环境变量的默认路径列表

  • /etc/paths.d/ contains files that hold additional search paths
  • /etc/paths.d/包含保存其他搜索路径的文件

Non-terminal programs don't inherit the system wide PATH and MANPATH variables that your terminal does! To set environment for all processes launched by a specific user, thus making environment variables available to Mac OS X GUI applications, those variables must be defined in your ~/.MacOSX/environment.plist (Apple Technical Q&A QA1067)

非终端程序不会继承终端执行的系统范围的PATH和MANPATH变量!要为特定用户启动的所有进程设置环境,从而使环境变量可用于Mac OS X GUI应用程序,必须在〜/ .MacOSX / environment.plist中定义这些变量(Apple Technical Q&A QA1067)

Use the following command line to synchronize your environment.plist with /etc/paths:

使用以下命令行将environment.plist与/ etc / paths同步:

defaults write $HOME/.MacOSX/environment PATH "$(tr '\n' ':' </etc/paths)"

#18


5  

the $PATH variable is also subject to path_helper, which in turn makes use of the /etc/paths file and files in /etc/paths.d.

$ PATH变量也受path_helper的约束,而path_helper又使用/ etc / paths文件和/etc/paths.d中的文件。

A more thorough description can be found here: http://hea-www.harvard.edu/~fine/OSX/path_helper.html

可以在这里找到更详尽的描述:http://hea-www.harvard.edu/~fine/OSX/path_helper.html

#19


3  

Setup your PATH environment variable on Mac OS

Open the Terminal program (this is in your Applications/Utilites folder by default). Run the following command touch ~/.bash_profile; open ~/.bash_profile This will open the file in the your default text editor.

打开终端程序(默认位于Applications / Utilites文件夹中)。执行以下命令touch~ / .bash_profile; open~ / .bash_profile这将在您的默认文本编辑器中打开该文件。

For ANDROID SDK as example :

以ANDROID SDK为例:

You need to add the path to your Android SDK platform-tools and tools directory. In my example I will use "/Development/android-sdk-macosx" as the directory the SDK is installed in. Add the following line:

您需要添加Android SDK平台工具和工具目录的路径。在我的示例中,我将使用“/ Development / android-sdk-macosx”作为安装SDK的目录。添加以下行:

export PATH=${PATH}:/Development/android-sdk-macosx/platform-tools:/Development/android-sdk-macosx/tools

Save the file and quit the text editor. Execute your .bash_profile to update your PATH.

保存文件并退出文本编辑器。执行.bash_profile以更新PATH。

source ~/.bash_profile

Now everytime you open the Terminal program you PATH will included the Android SDK.

现在每次打开终端程序时,PATH都会包含Android SDK。

#20


3  

It's simple:

Edit ~/.profile and put your variables as follow

编辑〜/ .profile并将变量放在下面

$ vim ~/.profile

$ vim~ / .profile

In file put:

在文件中:

MY_ENV_VAR=value

  1. Save ( :wq )

    保存(:wq)

  2. Restart the terminal (Quit and open it again)

    重启终端(退出并再次打开)

  3. Make sure that`s all be fine:

    确保一切都很好:

$ echo $MY_ENV_VAR

$ echo $ MY_ENV_VAR

$ value


#21


3  

/etc/launchd.conf is not used in Yosemite, El Capitain, or (High) Sierra

From the launchctl man page:

从launchctl手册页:

/etc/launchd.conf file is no longer consulted for subcommands to run during early boot time;
this functionality was removed for security considerations.

The method described in this Ask Different answer works for me (after a reboot): applications launched from the Dock or from Spotlight inherit environment variables that I set in ~/Library/LaunchAgents/my.startup.plist. (In my case, I needed to set LANG, to en_US.UTF-8, for a Sublime Text plugin.)

此Ask Ask中描述的方法适用于我(重启后):从Dock或Spotlight启动的应用程序继承了我在〜/ Library / LaunchAgents / my.startup.plist中设置的环境变量。 (就我而言,我需要将LANG设置为en_US.UTF-8,用于Sublime Text插件。)

#22


3  

For a single user modification, use ~/.profile of the ones you listed. The following link explains when the different files are read by Bash.

对于单个用户修改,请使用您列出的〜/ .profile。以下链接说明了Bash读取不同文件的时间。

http://telin.ugent.be/~slippens/drupal/bashrc_and_others

If you want to set the environment variable for gui applications you need the ~/.MacOSX/environment.plist file

如果要为gui应用程序设置环境变量,则需要〜/ .MacOSX / environment.plist文件

#23


3  

Well, I'm unsure about the /etc/paths and ~/.MacOSX/environment.plist files. Those are new.

好吧,我不确定/ etc / paths和〜/ .MacOSX / environment.plist文件。那是新的。

But with Bash, you should know that .bashrc is executed with every new shell invocation and .bash_profile is only executed once at startup.

但是对于Bash,你应该知道.bashrc是在每次新的shell调用时执行的.bash_profile只在启动时执行一次。

I don't know how often this is with Mac OS X. I think the distinction has broken down with the window system launching everything.

我不知道Mac OS X的频率是多少。我认为这种区别已经打破了窗口系统启动一切。

Personally, I eliminate the confusion by creating a .bashrc file with everything I need and then do:

就个人而言,我通过创建一个包含我需要的所有内容的.bashrc文件来消除混淆,然后执行:

ln -s .bashrc .bash_profile

#24


2  

There are two type of shells at play here.

这里有两种类型的贝壳。

  • Non-Login: .bashrc is reloaded every time you start a new copy of bash
  • 非登录:每次启动bash的新副本时都会重新加载.bashrc

  • Login: The .profile is loaded only when you either login, or explicitly tell bash to load it and use it as a login shell.
  • 登录:.profile仅在您登录时加载,或者明确告诉bash加载它并将其用作登录shell。

Its important to understand here that with bash .bashrc is only read by a shell that's both interactive and non-login, and you will find that people often load .bashrc in .bash_profile to overcome this limitation.

重要的是要理解,使用bash .bashrc只能由一个既可以进行交互也可以进行非登录的shell读取,你会发现人们经常在.bash_profile中加载.bashrc来克服这个限制。

Now that you have the basic understanding, lets move on to how i would advice you to set it up.

既然您已经掌握了基本知识,那么我们将继续讨论如何建议您进行设置。

  • .profile: create it non-existing. Put your PATH setup in there.
  • .profile:创建它不存在。将PATH设置放在那里。

  • .bashrc: create if non-existing. Put all your Aliases and Custom method in there.
  • .bashrc:如果不存在则创建。将所有别名和自定义方法放在那里。

  • .bash_profile: create if non-existing. Put the following in there.
  • .bash_profile:如果不存在则创建。把以下内容放在那里。

.bash_file:

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

#25


2  

Login Shells

/etc/profile

The shell first executes the commands in /etc/profile. A user working with root privileges can set up this file to establish systemwide default characteristics for users running bash.

shell首先执行/ etc / profile中的命令。使用root权限的用户可以设置此文件,以便为运行bash的用户建立系统范围的默认特征。

.bash_profile 
.bash_login 
.profile

Next the shell looks for ~/.bash_profile, ~/.bash_login, and ~/.profile (~/ is short- hand for your home directory), in that order, executing the commands in the first of these files it finds. You can put commands in one of these files to override the defaults set in /etc/profile. A shell running on a virtual terminal does not execute commands in these files.

接下来,shell按顺序查找〜/ .bash_profile,〜/ .bash_login和〜/ .profile(〜/是您的主目录的简写),执行它找到的第一个文件中的命令。您可以将命令放在其中一个文件中,以覆盖/ etc / profile中设置的默认值。在虚拟终端上运行的shell不会在这些文件中执行命令。

.bash_logout

When you log out, bash executes commands in the ~/.bash_logout file. This file often holds commands that clean up after a session, such as those that remove temporary files.

当您注销时,bash会执行〜/ .bash_logout文件中的命令。此文件通常包含在会话后清理的命令,例如删除临时文件的命令。

Interactive Nonlogin Shells

交互式非登录外壳

/etc/bashrc

Although not called by bash directly, many ~/.bashrc files call /etc/bashrc. This setup allows a user working with root privileges to establish systemwide default characteristics for nonlogin bash shells.

虽然没有直接调用bash,但很多〜/ .bashrc文件调用/ etc / bashrc。此设置允许使用root权限的用户为非登录bash shell建立系统范围的默认特征。

.bashrc

An interactive nonlogin shell executes commands in the ~/.bashrc file. Typically a startup file for a login shell, such as .bash_profile, runs this file, so both login and nonlogin shells run the commands in .bashrc.

交互式非登录shell在〜/ .bashrc文件中执行命令。通常,登录shell的启动文件(例如.bash_profile)运行此文件,因此login和nonlogin shell都运行.bashrc中的命令。

Because commands in .bashrc may be executed many times, and because subshells inherit exported variables, it is a good idea to put commands that add to existing variables in the .bash_profile file.

因为.bashrc中的命令可能会执行多次,并且因为子shell继承了导出的变量,所以最好将添加到.bash_profile文件中的现有变量的命令。

#26


2  

One thing to note in addition to the approaches suggested is that, in OS X 10.5 (Leopard) at least, the variables set in launchd.conf will be merged with the settings made in .profile. I suppose this is likely to be valid for the settings in ~/.MacOSX/environment.plist too, but I haven't verified.

除了建议的方法之外,还有一点需要注意的是,至少在OS X 10.5(Leopard)中,launchd.conf中设置的变量将与.profile中的设置合并。我想这也可能对〜/ .MacOSX / environment.plist中的设置有效,但我还没有验证。

#27


1  

For Bash, try adding your environment variables to the file /etc/profile to make them available for all users. No need to reboot, just start a new Terminal session.

对于Bash,请尝试将环境变量添加到文件/ etc / profile中,以使其可供所有用户使用。无需重启,只需启动新的终端会话即可。

#28


1  

It's quite simple, edit .profile (vi, nano, sublimeText or other text editor) file, you can found it at ~/ directory (user directory) and set like this :

这很简单,编辑.profile(vi,nano,sublimeText或其他文本编辑器)文件,你可以在〜/ directory(用户目录)找到它并设置如下:

export MY_VAR=[your value here]

导出MY_VAR = [你的价值在这里]

exemple with java home :

例如java home:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/current

save it and return to the terminal.

保存并返回终端。

You can reload it with :

您可以使用以下命令重新加载:

source .profileor close / open your terminal window.

source .profileor关闭/打开您的终端窗口。

#29


1  

Just did this really easy and quick. First create a ~/.bash_profile from terminal:

这样做非常简单快捷。首先从终端创建一个〜/ .bash_profile:

touch .bash_profile

then

open -a TextEdit.app .bash_profile

add

export TOMCAT_HOME=/Library/Tomcat/Home

save documement and you are done.

保存文件,你就完成了。

#30


1  

All the Magic on IOS only goes with using source with the file, where you export your ENV-Variables.

IOS上的所有Magic都只使用source和文件,在那里导出ENV-Variables。

For Example:

You can create an File like this:

您可以像这样创建一个文件:

export bim=fooo
export bom=bar

Save this file as bimbom.env , and do source ./bimbom.ev Voilá, you got your ENV-Variables.

将此文件保存为bimbom.env,并执行./bimbom.evVoilá,您获得了ENV-Variables。

Check them with: echo $bim

检查它们:echo $ bim