Nice programing

OS X에서 환경 변수 설정

nicepro 2020. 9. 28. 10:06
반응형

OS X에서 환경 변수 설정


OS X에서 PATH와 같은 환경 변수를 수정하는 적절한 방법은 무엇입니까?

Google을 조금 살펴본 결과 편집 할 파일 3 개를 찾았습니다.

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

나는 이러한 파일 중 일부도 가지고 있지 않으며 OS X는 이제 bash를 사용하기 때문에 .tcshrc 가 잘못되었다고 확신합니다 . 이러한 변수, 특히 PATH는 어디에 정의되어 있습니까?

나는 실행 해요 OS X 10.5 (레오파드).


브루노는 올바른 길을 가고 있습니다. 광범위한 연구를 수행했으며 모든 GUI 응용 프로그램에서 사용할 수있는 변수를 설정하려는 경우 유일한 옵션은 /etc/launchd.conf.

참고하시기 바랍니다 environment.plist이 스포트 라이트를 통해 실행 된 응용 프로그램이 작동하지 않습니다. 이것은 여기에 Steve Sexton에 의해 문서화되었습니다 .

  1. 터미널 프롬프트 열기

  2. 유형 sudo vi /etc/launchd.conf(참고 :이 파일은 아직 존재하지 않을 수 있음)

  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://stackoverflow.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. vi에 변경 사항을 저장하고 Mac을 재부팅하십시오. 또는 위의 코드 주석에 표시된 grep/ xargs명령을 사용하십시오 .

  5. 터미널 창을 열고 입력하여 변수가 작동 export하는지 확인하면 새 변수가 표시되어야합니다. 이는 IntelliJ IDEA 및 Spotlight를 통해 실행하는 기타 GUI 응용 프로그램에서도 사용할 수 있습니다.


Spotlight에서 시작된 새 프로세스에 대한 환경을 설정하는 방법 (재부팅 할 필요 없음)

를 사용하여 launchd (및 확장으로 Spotlight에서 시작된 모든 항목)에서 사용하는 환경을 설정할 수 있습니다 launchctl setenv. 예를 들어 경로를 설정하려면 :

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

또는 경로를 설정하려면 .bashrc다음과 같이 미러링하십시오.

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

변경된 환경을 선택하려면 앱을 다시 시작해야하지만 재부팅 할 필요는 없습니다.

여기에는 Terminal.app에서 이미 실행중인 모든 셸이 포함되지만, 거기에 있다면 환경을 더 직접 설정할 수 있습니다 (예 : export PATH=/opt/local/bin:/opt/local/sbin:$PATHbash 또는 zsh 용).

재부팅 후 변경 사항을 유지하는 방법

재부팅 후에도 변경 사항유지 하려면 다음/etc/launchd.conf 과 같이 에서 환경 변수를 설정할 수 있습니다 .

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

launchd.conf 재부팅하면 자동으로 실행됩니다.

이러한 변경 사항을 지금 적용하려면이 명령을 사용하여 다시 처리해야합니다 launchctl.conf(팁 @mklement에게 감사드립니다!)

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

명령을 사용하여 launchctl로드하는 방법 에 대해 자세히 알아볼 수 있습니다 .launchd.confman launchctl


OS X v10.7 (Lion) 까지 포함하여 다음에서 설정할 수 있습니다.

~/.MacOSX/environment.plist

보다:

터미널의 PATH의 경우 .bash_profile또는 에서 설정할 수 있어야합니다 .profile(하지만 생성해야 할 수도 있음).

대한 OS X의 v10.8 (산 사자) 이후 사용할 필요 launchd하고launchctl .


단일 소스에서 명령 줄 및 GUI 응용 프로그램 모두를위한 솔루션 ( Mac OS X v10.10 (Yosemite) 및 Mac OS X v10.11 (El Capitan)에서 작동)

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

로그인 할 때마다 그리고 요청시 언제든지 이러한 변수를 사용자 세션에로드 할 Launch Agent 가 필요합니다 . 또한 이러한 정의를 구문 분석하고 에이전트가 실행하는 데 필요한 명령을 빌드하려면 셸 스크립트가 필요합니다.

가진 파일 만들기 plist(라는 이름의 예 접미사 osx-env-sync.plist)에 ~/Library/LaunchAgents/다음과 같은 내용으로 디렉토리를 :

<?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여기서 매개 변수는 매우 중요합니다. 그것은 함께 쉘 스크립트를 실행하는 데 필요한의 로그인 쉘 그래서 ~/.bash_profile이 스크립트가 실행되기 전에 처음에 공급된다.

이제 쉘 스크립트입니다. ~/.osx-env-sync.sh다음 내용으로 작성하십시오 .

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

쉘 스크립트가 실행 가능한지 확인하십시오.

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

이제 현재 세션에 대한 시작 에이전트를로드합니다.

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

(재) GUI 응용 프로그램을 시작하고 환경 변수를 읽을 수 있는지 확인합니다.

설정은 지속적입니다. 다시 시작하고 다시 로그인해도 유지됩니다.

초기 설정 (방금 수행) 후 ~/.bash_profile전체 환경의 변경 사항을 다시 반영 하려면 launchctl load ...명령을 다시 실행해도 원하는 작업이 수행되지 않습니다. 대신 다음과 같은 경고가 표시됩니다.

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

로그 아웃 / 로그인 프로세스를 거치지 않고 환경 변수를 다시로드하려면 다음을 수행하십시오.

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

마지막으로 이미 실행중인 응용 프로그램 (Terminal.app 포함)을 다시 시작하여 변경 사항을 인식하도록하십시오.

또한 여기에 코드와 설명을 GitHub 프로젝트 인 osx-env-sync로 푸시했습니다 .

나는 이것이 최소한 OS X의 최신 버전 (Yosemite & El Capitan)을위한 궁극적 인 해결책이되기를 바랍니다.


  1. 하다:

    vim ~/.bash_profile
    

    파일이 존재하지 않을 수 있습니다 (아니라면 그냥 만들 수 있습니다).

  2. 이것을 입력하고 파일을 저장하십시오.

    export PATH=$PATH:YOUR_PATH_HERE
    
  3. 운영

    source ~/.bash_profile
    

OS X에서 환경 변수를 처리 할 때 근본적으로 해결해야 할 두 가지 문제가 있습니다. 첫 번째는 Spotlight (Mac 메뉴 / 상태 표시 줄의 오른쪽에있는 돋보기 아이콘)에서 프로그램을 호출 할 때이고 두 번째는 Dock에서 프로그램을 호출 할 때입니다. . 이 표준 쉘 위치에서 환경을 읽기 때문에 터미널 응용 프로그램에서 프로그램을 호출 / 유틸리티 (사소한 ~/.profile, ~/.bash_profile, ~/.bashrc, 등)

Dock에서 프로그램을 호출 할 때 요소에 일련의 요소 가 포함 된 ~/.MacOSX/environment.plist위치를 사용 하십시오 .<dict><key>KEY</key><string>theValue</string>

Spotlight에서 프로그램을 호출 할 때 필요한 모든 키 / 값 설정으로 launchd가 설정되었는지 확인하십시오.

두 문제를 동시에 해결하기 위해 사용자 계정에서 로그인 항목 (시스템 환경 설정 도구를 통해 설정)을 사용합니다. 로그인 항목은 Emacs lisp 함수를 호출하는 bash 스크립트입니다. 물론 좋아하는 스크립팅 도구를 사용하여 동일한 작업을 수행 할 수 있습니다. 이 접근 방식은 언제든지 작동하고 재부팅 할 필요가 없다는 추가 이점이 있습니다. 즉 ~/.profile, 일부 셸에서 로그인 항목을 편집 하고 실행할 수 있으며 Dock 또는 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/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.


Another, free, opensource, Mac OS X v10.8 (Mountain Lion) Preference pane/environment.plist solution is 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.

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.

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

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


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

Apple's Developer Forums say:

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

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

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

Show Package Contents

And I 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)

Enter image description here

Now the application (in my case Sourcetree) uses the given path and works with Git 1.9.3 :-)

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


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.

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.

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


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.

Original answer

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

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:

sudo launchctl config user path <new path>

This option is documented in the launchctl man page:

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.

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.


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:

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

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.


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.

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.

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

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:

eval $(launchctl export)

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.


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.


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

  • Open up Terminal.
  • Run the following command:

    sudo nano /etc/paths or 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.
  • Enter 'Y' to save the modified buffer.
  • 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:

Add to the PATH on Mac OS X 10.8 Mountain Lion and up


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

Here you go:

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


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
  • /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.d/ contains files that hold additional search 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)

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

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

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.

A more thorough description can be found in PATH and other environment issues in Leopard (2008-11)


/etc/launchd.conf is not used in OS X v10.10 (Yosemite), OS X v10.11 (El Capitan), macOS v10.12 (Sierra), or macOS v10.13 (High Sierra).


From the launchctl man page:

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


It's simple:

Edit ~/.profile and put your variables as follow

$ vim ~/.profile

In file put:

MY_ENV_VAR=value

  1. Save ( :wq )

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

  3. Make sure that`s all be fine:

$ echo $MY_ENV_VAR

$ value



For a single user modification, use ~/.profile of the ones you listed. The following link explains when the different files are read by 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


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

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

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.

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

ln -s .bashrc .bash_profile

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.


Set up your PATH environment variable on Mac OS

Open the Terminal program (this is in your Applications/Utilities folder by default). Run the following command

touch ~/.bash_profile; open ~/.bash_profile

This will open the file in the your default text editor.

For Android SDK as example:

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:

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:

source ~/.bash_profile

Now every time you open the Terminal program your PATH will include the Android SDK.


There are two type of shells at play here.

  • Non-login: .bashrc is reloaded every time you start a new copy of 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.

It's important to understand here that with Bash, file .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.

Now that you have the basic understanding, let’s move on to how I would advice you to set it up.

  • .profile: create it non-existing. Put your PATH setup in there.
  • .bashrc: create if non-existing. Put all your aliases and custom methods in there.
  • .bash_profile: create if non-existing. Put the following in there.

.bash_file:

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

Login Shells

/etc/profile

The shell first executes the commands in file /etc/profile. A user working with root privileges can set up this file to establish systemwide default characteristics for users running 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_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.

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.

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

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.


All the magic on iOS only goes with using source with the file, where you export your environment 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 environment variables.

Check them with:

echo $bim

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

touch .bash_profile

then

open -a TextEdit.app .bash_profile

add

export TOMCAT_HOME=/Library/Tomcat/Home

save documement and you are done.


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.


It's quite simple. Edit file .profile (vi, nano, Sublime Text or other text editor) file. You can found it at the ~/ directory (user directory) and set like this:

export MY_VAR=[your value here]

Example with Java home:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/current

Save it and return to the terminal.

You can reload it with:

source .profile

Or close and open your terminal window.

참고URL : https://stackoverflow.com/questions/135688/setting-environment-variables-on-os-x

반응형