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

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

/etc/paths ~ / . profile ~ / tcshrc

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

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


当前回答

更新(2017-08-04)

从macOS 10.12.6 (Sierra)开始,这个方法似乎已经停止在Apache httpd上工作(对于系统和launchctl配置的用户选项)。其他项目似乎没有受到影响。可以想象,这是httpd中的一个bug。

原来的答案

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

我在很多地方读到过,使用launchctl setenv PATH <new PATH >来设置PATH变量由于OS X中的一个错误而不起作用(从个人经验来看似乎是正确的)。我发现还有另一种方法可以为非shell启动的应用程序设置PATH:

sudo launchctl config user path <new path>

这个选项记录在launchctl手册页中:

config system | user parameter value Sets persistent configuration information for launchd(8) domains. Only the system domain and user domains may be configured. The location of the persistent storage is an implementation detail, and changes to that storage should only be made through this subcommand. A reboot is required for changes made through this subcommand to take effect. [...] path Sets the PATH environment variable for all services within the target domain to the string value. The string value should conform to the format outlined for the PATH environment variable in environ(7). Note that if a service specifies its own PATH, the service-specific environment variable will take precedence. NOTE: This facility cannot be used to set general environment variables for all services within the domain. It is intentionally scoped to the PATH environment vari- able and nothing else for security reasons.

我已经确认这与从Finder(使用getenv获取PATH)开始的GUI应用程序一起工作。 请注意,您只需要这样做一次,并且更改将在重新启动时保持不变。

其他回答

在Mountain Lion上,所有的/etc/paths和/etc/launchd.conf编辑都不起任何作用!

苹果的开发者论坛说:

“更改信息。.app本身的plist包含一个“lsenvirenvironment” 带有所需环境变量的字典。 ~ / .MacOSX /环境。不再支持Plist。”

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

我添加了一个新的键/字典对,称为:

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

(参见苹果的LaunchServicesKeys文档)

现在应用程序(在我的例子中是Sourcetree)使用给定的路径并使用Git 1.9.3:-)

PS:当然,您必须调整路径条目以满足您特定的路径需求。

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

export MY_VAR=[your value here]

Java home的示例:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/current

保存它并返回到终端。

你可以用:

source .profile

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

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

My .bash_profile consists solely of one line, (This is just personal preference.) source .bashrc My .bashrc has this: function export() { builtin export "$@" if [[ ${#@} -eq 1 && "${@//[^=]/}" ]] then launchctl setenv "${@%%=*}" "${@#*=}" elif [[ ! "${@//[^ ]/}" ]] then launchctl setenv "${@}" "${!@}" fi } export -f export 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: 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 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. 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.

虽然这里的答案并不是“错误的”,但我还要补充一点:永远不要在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 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.

不管“蹩脚”与否,如果您将这些更改限制在较小的范围内,您将拥有一个更加稳定的系统。

在处理时,基本上有两个问题需要解决 第一个是在调用程序时 来自Spotlight (Mac右侧的放大镜图标) 菜单/状态栏),第二个是从Dock调用程序。 从终端应用程序/实用程序调用程序非常简单 因为它从标准shell位置读取环境 (~ /。简介~ /。bash_profile、~ /。bashrc,(等等)。

当从Dock调用程序时,使用~/.MacOSX/environment.plist <dict>元素包含序列 <键>键< /关键> <字符串> < /字符串>价值元素。

当从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.

细节:

登录项:~/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功能:~/lib/ Emacs /elisp/macosx/ environment -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)))

注意:这个解决方案是在我添加我的解决方案之前的一个混合体,特别是由Matt Curtis提供的解决方案,但我故意试图保持我的~/。bash_profile独立于内容平台,并将launchd环境(Mac专用工具)的设置放到单独的脚本中。