在OS X中设置环境变量?

时间:2022-02-23 02:06:03

What is the proper way to modify environment variables like PATH in OSX? I've looked on Google a little bit and found 3 different files to edit:

在OSX中修改环境变量的正确方法是什么?我看了谷歌,发现了三个不同的文件编辑:

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

I don't even have some of these files, and I'm pretty sure that .tcshrc is wrong, since OSX uses bash now. Anybody have any idea where these variables, especially PATH, are defined?

我甚至没有这些文件,我很确定。tcshrc是错误的,因为OSX现在使用bash。有没有人知道这些变量,特别是路径,是怎么定义的?

Edit: I'm running OS X 10.5

编辑:我运行OS X 10.5。

29 个解决方案

#1


602  

Bruno is right on track. I've done extensive research and if you want to set variables that are available in all GUI apps, 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.

请注意环境。plist不适用于通过Spotlight启动的应用程序。这是Steve Sexton在这里记录的。

1) Open a terminal prompt

1)打开终端提示。

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

2)类型sudo vi /etc/launchd。conf(注意:这个文件可能还不存在)

3) Put contents like the following into the file

3)将以下内容放入文件中。

# 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 enviroment 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.

4)在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 and other GUI apps you launch via Spotlight.

5)证明你的变量是通过打开一个终端窗口和输入导出来工作的,你应该看到你的新变量。这些也将在IntelliJ和其他你通过Spotlight发布的GUI应用程序中得到。

#2


241  

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(以及从聚光灯开始的任何东西)所使用的环境。例如设置路径:

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.

这包括已经在终端运行的任何shell。应用程序,如果你在那里,你可以更直接地设置环境,例如,用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设置环境变量。相依,像这样:

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。参看(感谢@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.

您可以了解关于launchctl的更多信息,以及它如何加载launchd。和指挥员一起发射。

#3


102  

Up to and including Lion (10.7) you can set them in

包括狮子(10.7),你可以把它们放进去。

~/.MacOSX/environment.plist

~ / .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)

对于终端中的路径,您应该能够设置.bash_profile或.profile(您可能需要创建它)

For Mountain lion and beyond you need to use launchd and launchctl

对于美洲狮,你需要使用launchd和launchctl。

#4


55  

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负载…命令不会执行你想要的;相反,你会得到如下警告:

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

< $ HOME > /图书馆/ 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.

最后,确保您重新启动已经运行的应用程序(包括终端应用程序),以使它们了解更改。

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


46  

1.

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

3.运行

source ~/.bash_profile

#6


32  

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位置读取环境(~/。简介~ /。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 /环境。plist,其中 元素包含一个 key theValue 元素的序列。

When invoking programs from Spotlight, insure 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.

为了同时解决这两个问题,我在我的用户帐户上使用一个登录项(通过系统首选项工具设置)。登录项是一个bash脚本,它调用Emacs lisp函数,当然也可以使用他们最喜欢的脚本工具来完成相同的任务。这种方法有额外的好处,它可以在任何时候工作,不需要重新启动,也就是说可以编辑~/。配置文件,在一些shell中运行登录项,并对新调用的程序(从Dock或Spotlight)可见更改。

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.

注意:这个解决方案是在我添加我的之前,特别是马特·柯蒂斯提供的,但我故意试图保持我的~/。bash_profile内容平*立,并将launchd环境(一个Mac的唯一设施)设置为单独的脚本。

#7


21  

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

另一个免费的opensource Mac OSX Mountain Lion(10.8)偏好面板/环境。EnvPane plist解决方案。

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.

在Github上可以找到EnvPane的源代码。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)的首选面板,它允许您为图形化和终端会话中的所有程序设置环境变量。它不仅恢复了对~/. macosx /环境的支持。plist在Mountain Lion中,它也会立即发布您对环境的更改,而不需要注销和返回。 EnvPane包括(并自动安装)一个在登录后运行早期的launchd代理,以及每当~/. macosx /环境时。plist变化。代理读取~ / .MacOSX /环境。plist并将环境变量从该文件导出到当前用户的launchd实例,该API由launchctl setenv和launchctl unsetenv使用。

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

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

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

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

#8


17  

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

在Mountain Lion上,所有的/etc/路径和/etc/launchd。conf编辑没有任何效果!

Apple's Developer Forums say:

苹果的开发者论坛上说:

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

“改变的信息。应用程序的plist本身包含一个“LSEnvironment”字典和您想要的环境变量。

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

~ / .MacOSX /环境。plist不再被支持。

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

所以我直接编辑了app的信息。plist(右击“AppName”)。应用程序(在本例中是SourceTree),然后是“显示包内容”)

在OS X中设置环境变量?

and added a new key/dict pair called:

并添加了一个新的密钥/命令对:

<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 :-)

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

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

PS:当然你必须调整路径进入到你的特定路径需要。

#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."

根据我的经验,对环境变量的全局更改,比如所有进程的路径,在OS X上的破坏比在Windows上更有可能。原因是,大量的OS X应用程序和其他软件(包括,也许特别是组件的操作系统本身)依赖的UNIX命令行工具引擎盖下,和假设的行为这些工具提供了系统的版本,不一定使用绝对路径,当这样做(类似评论适用于动态加载的库和DYLD_ *环境变量)。例如,考虑到对各种堆栈溢出问题的*别的答案,比如用Python和Ruby替换OS x提供的解释器的版本,通常会说“不要这样做”。

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)没有什么不同;苹果不提供一种简单的方法的最可能的原因是它打破了一切。的窗户不容易出现这些问题,这是由于两件事:(1)Windows软件并不倾向于依靠UNIX命令行工具的软件,和(2)微软有这样一个广泛的历史“DLL地狱”和安全问题造成的影响所有进程的变化,他们改变了行为的动态加载新的Windows版本限制“全球”配置选项的影响路径。

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

“跛脚”,如果你把这些变化限制在更小的范围内,你将拥有一个更稳定的系统。

#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 the only thing that works for me in this case is:

有时候,之前所有的答案都是行不通的。如果你想在Eclipse或IntelliJ中访问一个系统变量(比如M2_HOME),那么在这个例子中唯一适合我的是:

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

第一步(第一步)编辑/etc/launchd。conf包含这样的一行:“setenv VAR值”然后(步骤2)重新启动。

Simply modifying .bash_profile won't work because in osx the applications are not started as in other UNIX'es, they don't inherit the parents 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不会起作用,因为在osx中,应用程序不像在其他UNIX中那样启动,它们不会继承父类变量。所有其他的修改都不会起作用,因为我不知道这个原因。也许其他人可以澄清这件事。

#11


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.

在追踪了环境变量偏好窗格之后,发现链接被打破,并且在苹果的网站上搜索似乎表明他们已经忘记了……我回到了难以捉摸的launchd过程。

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)中显示了在环境中定义的变量。plist被可靠地导出到来自Spotlight的应用程序(通过launchd)。我的问题是那些vars没有被导出到终端的新bash会话中。也就是说,我有一个相反的问题。

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

注:环境。如前所述,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/环境来获得Spotlight应用程序来查看vars。plist和我可以将相同的vars添加到一个新的终端会话中,通过添加下面的.profile文件:

eval $(launchctl export)

#12


13  

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配置的用户选项)。其他项目似乎没有受到影响。可以想象,这是httpd中的一个bug。

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不再可写的rootless模式)。

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变量,因为OS X中的一个bug(从个人经验看来是如此),所以不能工作。我发现有另一种方法可以为不从shell中启动的应用程序设置路径:

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.

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

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来获取路径)。请注意,您只需要执行一次,而更改将通过重新启动来持久。

#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。还有一些奇怪的文件叫做~/. macosx /环境。用于GUI应用程序中的环境变量的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构建的“导出”超载,并将正常输出(您会注意到我导出了“export”!),然后通过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,我可以只设置my .bash_profile / .bashrc设置我想要的方式。打开一个终端窗口,查看您感兴趣的环境变量,使用launchctl getenv myVar,更改您的.bash_profile/。关闭终端窗口并重新打开它,用launchctl再次检查变量,瞧,它已经改变了。

  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)

这里有一个很简单的方法来做你想做的事情。在我的例子中,它是让gradle工作(对于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/path。

  • 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

您应该看到在路径末尾添加的新路径。

I got these details from this post:

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

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

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 what the OP is looking for is a simple, windows-like solution.

我认为OP是寻找一个简单的,windows-like解决方案。

here ya go:

这丫去:

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

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
  • ~ /。每个时间终端都有配置文件。应用程序启动
  • ~/.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/ PATH是Mac OS中的主要文件,其中包含为所有用户构建PATH环境变量的默认路径列表。
  • /etc/paths.d/ contains files that hold additional search paths
  • /etc/paths.包含包含其他搜索路径的文件。

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)

非终端程序不会继承您的终端所做的系统宽路径和MANPATH变量!要为特定用户启动的所有进程设置环境,从而使MacOSX GUI应用程序可以使用环境变量,这些变量必须在您的~/. macosx /环境中定义。plist (Apple Technical Q&A QA1067)

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

使用以下命令行来同步您的环境。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的约束,后者反过来使用/etc/ PATH文件和/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  

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

对于单个用户修改,使用~/。您所列出的文件的概要文件,下面的链接解释了bash读取不同文件时的情况。

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

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 /环境。plist文件

#20


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.

打开终端程序(默认情况下,这是在您的应用程序/使用文件夹中)。运行以下命令触摸~/.bash_profile;~ /开放。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平台工具和工具目录添加路径。在我的例子中,我将使用“/开发/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以更新路径。

source ~/.bash_profile

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

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

#21


3  

It's simple:

很简单:

Edit ~/.profile and put your variables as follow

编辑~ /。配置文件并将您的变量设置为follow。

$ vim ~/.profile

vim美元~ / . profile

In file put:

在文件:

MY_ENV_VAR=value

MY_ENV_VAR =值

  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

回声MY_ENV_VAR美元

$ value

美元的价值


#22


2  

well, I'm unsure about /etc/paths and ~/.MacOSX/environment.plist those are new.

嗯,我不确定/etc/路径和~/. macosx /环境。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. Don't know how often this is with macos, I think the distinction has broken down with the window system launching everything.

但是在bash中,您应该知道。bashrc是在每个新的shell调用中执行的,并且。bash_profile只在启动时执行一次。不知道这与macos的频率有多高,我想这个区别已经打破了,窗口系统启动了一切。

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

就我个人而言,我通过创建一个.bashrc来消除混乱,然后做如下工作:

ln -s .bashrc .bash_profile

#23


2  

One thing to note in addition to the approaches suggested is that, in OS X 10.5 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中,至少在launchd中设置了变量。conf将与.profile中的设置合并。我想这可能对~/. macosx /环境中的设置有效。plist也是,但我还没核实。

#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
  • 非登录:.bashrc每次启动新的bash副本时都会重新加载。
  • 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:不存在创建它。设置路径设置。
  • .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:

.bash_file:

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

#25


2  

Login Shells

登录shell

/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中执行命令。使用根权限的用户可以设置此文件,为运行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.

接下来,壳牌寻找~/。bash_profile、~ /。bash_login和~ /。概要文件(~/是您的主目录的短指针),按照该顺序,在第一个文件中执行命令。您可以将命令放在其中一个文件中,以覆盖/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

交互式Nonlogin贝壳

/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.

虽然没有直接调用,但是很多~/。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)运行这个文件,因此登录和非登录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


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文件中,以使它们对所有用户都可用。无需重新启动,只需启动一个新的终端会话。

#27


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或其他文本编辑器)文件,你可以在~/目录(用户目录)找到它,然后设置如下:

export MY_VAR=[your value here]

出口MY_VAR =(你的价值在这里)

exemple with java home :

示例java home:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/current

出口JAVA_HOME = /图书馆/ Java / JavaVirtualMachines /电流

save it and return to the terminal.

保存并返回到终端。

You can reload it with :

你可以用:

source .profileor close / open your terminal window.

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

#28


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.

保存文档,您就完成了。

#29


1  

/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.)

在这个问题中所描述的方法在我(在重新启动后)中使用了不同的答案:从Dock或Spotlight中启动的应用程序继承了我在~/库/LaunchAgents/my.startup.plist中设置的环境变量。(在我的例子中,我需要设置LANG,以en_US。UTF-8,一个卓越的文本插件。

#1


602  

Bruno is right on track. I've done extensive research and if you want to set variables that are available in all GUI apps, 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.

请注意环境。plist不适用于通过Spotlight启动的应用程序。这是Steve Sexton在这里记录的。

1) Open a terminal prompt

1)打开终端提示。

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

2)类型sudo vi /etc/launchd。conf(注意:这个文件可能还不存在)

3) Put contents like the following into the file

3)将以下内容放入文件中。

# 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 enviroment 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.

4)在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 and other GUI apps you launch via Spotlight.

5)证明你的变量是通过打开一个终端窗口和输入导出来工作的,你应该看到你的新变量。这些也将在IntelliJ和其他你通过Spotlight发布的GUI应用程序中得到。

#2


241  

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(以及从聚光灯开始的任何东西)所使用的环境。例如设置路径:

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.

这包括已经在终端运行的任何shell。应用程序,如果你在那里,你可以更直接地设置环境,例如,用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设置环境变量。相依,像这样:

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。参看(感谢@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.

您可以了解关于launchctl的更多信息,以及它如何加载launchd。和指挥员一起发射。

#3


102  

Up to and including Lion (10.7) you can set them in

包括狮子(10.7),你可以把它们放进去。

~/.MacOSX/environment.plist

~ / .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)

对于终端中的路径,您应该能够设置.bash_profile或.profile(您可能需要创建它)

For Mountain lion and beyond you need to use launchd and launchctl

对于美洲狮,你需要使用launchd和launchctl。

#4


55  

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负载…命令不会执行你想要的;相反,你会得到如下警告:

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

< $ HOME > /图书馆/ 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.

最后,确保您重新启动已经运行的应用程序(包括终端应用程序),以使它们了解更改。

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


46  

1.

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

3.运行

source ~/.bash_profile

#6


32  

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位置读取环境(~/。简介~ /。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 /环境。plist,其中 元素包含一个 key theValue 元素的序列。

When invoking programs from Spotlight, insure 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.

为了同时解决这两个问题,我在我的用户帐户上使用一个登录项(通过系统首选项工具设置)。登录项是一个bash脚本,它调用Emacs lisp函数,当然也可以使用他们最喜欢的脚本工具来完成相同的任务。这种方法有额外的好处,它可以在任何时候工作,不需要重新启动,也就是说可以编辑~/。配置文件,在一些shell中运行登录项,并对新调用的程序(从Dock或Spotlight)可见更改。

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.

注意:这个解决方案是在我添加我的之前,特别是马特·柯蒂斯提供的,但我故意试图保持我的~/。bash_profile内容平*立,并将launchd环境(一个Mac的唯一设施)设置为单独的脚本。

#7


21  

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

另一个免费的opensource Mac OSX Mountain Lion(10.8)偏好面板/环境。EnvPane plist解决方案。

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.

在Github上可以找到EnvPane的源代码。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)的首选面板,它允许您为图形化和终端会话中的所有程序设置环境变量。它不仅恢复了对~/. macosx /环境的支持。plist在Mountain Lion中,它也会立即发布您对环境的更改,而不需要注销和返回。 EnvPane包括(并自动安装)一个在登录后运行早期的launchd代理,以及每当~/. macosx /环境时。plist变化。代理读取~ / .MacOSX /环境。plist并将环境变量从该文件导出到当前用户的launchd实例,该API由launchctl setenv和launchctl unsetenv使用。

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

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

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

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

#8


17  

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

在Mountain Lion上,所有的/etc/路径和/etc/launchd。conf编辑没有任何效果!

Apple's Developer Forums say:

苹果的开发者论坛上说:

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

“改变的信息。应用程序的plist本身包含一个“LSEnvironment”字典和您想要的环境变量。

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

~ / .MacOSX /环境。plist不再被支持。

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

所以我直接编辑了app的信息。plist(右击“AppName”)。应用程序(在本例中是SourceTree),然后是“显示包内容”)

在OS X中设置环境变量?

and added a new key/dict pair called:

并添加了一个新的密钥/命令对:

<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 :-)

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

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

PS:当然你必须调整路径进入到你的特定路径需要。

#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."

根据我的经验,对环境变量的全局更改,比如所有进程的路径,在OS X上的破坏比在Windows上更有可能。原因是,大量的OS X应用程序和其他软件(包括,也许特别是组件的操作系统本身)依赖的UNIX命令行工具引擎盖下,和假设的行为这些工具提供了系统的版本,不一定使用绝对路径,当这样做(类似评论适用于动态加载的库和DYLD_ *环境变量)。例如,考虑到对各种堆栈溢出问题的*别的答案,比如用Python和Ruby替换OS x提供的解释器的版本,通常会说“不要这样做”。

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)没有什么不同;苹果不提供一种简单的方法的最可能的原因是它打破了一切。的窗户不容易出现这些问题,这是由于两件事:(1)Windows软件并不倾向于依靠UNIX命令行工具的软件,和(2)微软有这样一个广泛的历史“DLL地狱”和安全问题造成的影响所有进程的变化,他们改变了行为的动态加载新的Windows版本限制“全球”配置选项的影响路径。

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

“跛脚”,如果你把这些变化限制在更小的范围内,你将拥有一个更稳定的系统。

#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 the only thing that works for me in this case is:

有时候,之前所有的答案都是行不通的。如果你想在Eclipse或IntelliJ中访问一个系统变量(比如M2_HOME),那么在这个例子中唯一适合我的是:

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

第一步(第一步)编辑/etc/launchd。conf包含这样的一行:“setenv VAR值”然后(步骤2)重新启动。

Simply modifying .bash_profile won't work because in osx the applications are not started as in other UNIX'es, they don't inherit the parents 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不会起作用,因为在osx中,应用程序不像在其他UNIX中那样启动,它们不会继承父类变量。所有其他的修改都不会起作用,因为我不知道这个原因。也许其他人可以澄清这件事。

#11


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.

在追踪了环境变量偏好窗格之后,发现链接被打破,并且在苹果的网站上搜索似乎表明他们已经忘记了……我回到了难以捉摸的launchd过程。

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)中显示了在环境中定义的变量。plist被可靠地导出到来自Spotlight的应用程序(通过launchd)。我的问题是那些vars没有被导出到终端的新bash会话中。也就是说,我有一个相反的问题。

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

注:环境。如前所述,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/环境来获得Spotlight应用程序来查看vars。plist和我可以将相同的vars添加到一个新的终端会话中,通过添加下面的.profile文件:

eval $(launchctl export)

#12


13  

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配置的用户选项)。其他项目似乎没有受到影响。可以想象,这是httpd中的一个bug。

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不再可写的rootless模式)。

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变量,因为OS X中的一个bug(从个人经验看来是如此),所以不能工作。我发现有另一种方法可以为不从shell中启动的应用程序设置路径:

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.

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

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来获取路径)。请注意,您只需要执行一次,而更改将通过重新启动来持久。

#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。还有一些奇怪的文件叫做~/. macosx /环境。用于GUI应用程序中的环境变量的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构建的“导出”超载,并将正常输出(您会注意到我导出了“export”!),然后通过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,我可以只设置my .bash_profile / .bashrc设置我想要的方式。打开一个终端窗口,查看您感兴趣的环境变量,使用launchctl getenv myVar,更改您的.bash_profile/。关闭终端窗口并重新打开它,用launchctl再次检查变量,瞧,它已经改变了。

  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)

这里有一个很简单的方法来做你想做的事情。在我的例子中,它是让gradle工作(对于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/path。

  • 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

您应该看到在路径末尾添加的新路径。

I got these details from this post:

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

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

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 what the OP is looking for is a simple, windows-like solution.

我认为OP是寻找一个简单的,windows-like解决方案。

here ya go:

这丫去:

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

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
  • ~ /。每个时间终端都有配置文件。应用程序启动
  • ~/.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/ PATH是Mac OS中的主要文件,其中包含为所有用户构建PATH环境变量的默认路径列表。
  • /etc/paths.d/ contains files that hold additional search paths
  • /etc/paths.包含包含其他搜索路径的文件。

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)

非终端程序不会继承您的终端所做的系统宽路径和MANPATH变量!要为特定用户启动的所有进程设置环境,从而使MacOSX GUI应用程序可以使用环境变量,这些变量必须在您的~/. macosx /环境中定义。plist (Apple Technical Q&A QA1067)

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

使用以下命令行来同步您的环境。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的约束,后者反过来使用/etc/ PATH文件和/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  

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

对于单个用户修改,使用~/。您所列出的文件的概要文件,下面的链接解释了bash读取不同文件时的情况。

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

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 /环境。plist文件

#20


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.

打开终端程序(默认情况下,这是在您的应用程序/使用文件夹中)。运行以下命令触摸~/.bash_profile;~ /开放。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平台工具和工具目录添加路径。在我的例子中,我将使用“/开发/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以更新路径。

source ~/.bash_profile

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

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

#21


3  

It's simple:

很简单:

Edit ~/.profile and put your variables as follow

编辑~ /。配置文件并将您的变量设置为follow。

$ vim ~/.profile

vim美元~ / . profile

In file put:

在文件:

MY_ENV_VAR=value

MY_ENV_VAR =值

  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

回声MY_ENV_VAR美元

$ value

美元的价值


#22


2  

well, I'm unsure about /etc/paths and ~/.MacOSX/environment.plist those are new.

嗯,我不确定/etc/路径和~/. macosx /环境。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. Don't know how often this is with macos, I think the distinction has broken down with the window system launching everything.

但是在bash中,您应该知道。bashrc是在每个新的shell调用中执行的,并且。bash_profile只在启动时执行一次。不知道这与macos的频率有多高,我想这个区别已经打破了,窗口系统启动了一切。

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

就我个人而言,我通过创建一个.bashrc来消除混乱,然后做如下工作:

ln -s .bashrc .bash_profile

#23


2  

One thing to note in addition to the approaches suggested is that, in OS X 10.5 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中,至少在launchd中设置了变量。conf将与.profile中的设置合并。我想这可能对~/. macosx /环境中的设置有效。plist也是,但我还没核实。

#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
  • 非登录:.bashrc每次启动新的bash副本时都会重新加载。
  • 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:不存在创建它。设置路径设置。
  • .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:

.bash_file:

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

#25


2  

Login Shells

登录shell

/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中执行命令。使用根权限的用户可以设置此文件,为运行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.

接下来,壳牌寻找~/。bash_profile、~ /。bash_login和~ /。概要文件(~/是您的主目录的短指针),按照该顺序,在第一个文件中执行命令。您可以将命令放在其中一个文件中,以覆盖/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

交互式Nonlogin贝壳

/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.

虽然没有直接调用,但是很多~/。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)运行这个文件,因此登录和非登录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


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文件中,以使它们对所有用户都可用。无需重新启动,只需启动一个新的终端会话。

#27


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或其他文本编辑器)文件,你可以在~/目录(用户目录)找到它,然后设置如下:

export MY_VAR=[your value here]

出口MY_VAR =(你的价值在这里)

exemple with java home :

示例java home:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/current

出口JAVA_HOME = /图书馆/ Java / JavaVirtualMachines /电流

save it and return to the terminal.

保存并返回到终端。

You can reload it with :

你可以用:

source .profileor close / open your terminal window.

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

#28


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.

保存文档,您就完成了。

#29


1  

/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.)

在这个问题中所描述的方法在我(在重新启动后)中使用了不同的答案:从Dock或Spotlight中启动的应用程序继承了我在~/库/LaunchAgents/my.startup.plist中设置的环境变量。(在我的例子中,我需要设置LANG,以en_US。UTF-8,一个卓越的文本插件。