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

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

/etc/paths ~ / . profile ~ / tcshrc

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

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


当前回答

任何Bash启动文件—~/。bashrc,(~ /。bash_profile、~ / . profile。还有一些奇怪的文件,名为~/. macosx /environment。用于GUI应用程序中的环境变量。

其他回答

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

$PATH变量也受制于path_helper,它反过来利用/etc/paths文件和/etc/paths.d中的文件

更详细的描述可以在PATH和Leopard(2008-11)的其他环境问题中找到。

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

~ /。概要文件是每次终端源。App上线 ~ /。bashrc是“传统上”设置Bash环境的所有导出语句的地方 /etc/paths是Mac OS中的主文件,包含为所有用户构建PATH环境变量的默认路径列表 /etc/paths.D /包含包含其他搜索路径的文件

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

使用以下命令行同步您的环境。Plist /etc/paths:

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

就像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.

做的事: vim ~ / . bash_profile 文件可能不存在(如果不存在,您可以直接创建它)。 输入并保存文件: 导出路径= $路径:YOUR_PATH_HERE 运行 源~ / . bash_profile