Setting environment variables on OS X

后端 未结 30 3168
你的背包
你的背包 2020-11-21 05:15

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

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

30条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 05:46

    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:

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

      source .bashrc
      
    2. My .bashrc has this:

      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:

      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.

    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.

提交回复
热议问题