MacOSX中設置和改變$PATH變量

什麼是$PATH

$PATH是Linux,OS X,Unix,Windows上的一個環境變量。$PATH變量通過冒號(:)分隔目錄地址。如果要打印當前的設置,打開終端輸入:

echo "$PATH"
或者

printf "%s\n" $PATH
OSX下改變你的PATH環境變量

你可以使用下面的任一方法

$HOME/.bash_profile 文件使用了export語法。
/etc/paths.d 目錄
方法1: $HOME/.bash_profile 文件

它的語法如下:

export PATH=$PATH:/new/dir/location1
export PATH=$PATH:/new/dir1:/dir2:/dir/path/no3
舉個例子,添加/usr/local/sbin/mypath這個目錄到$PATH變量。編輯 $HOME/.bash_profile 文件,終端輸入

vi $HOME/.bash_profile
或者

vi ~/.bash_profile
添加下面的export命令:

export PATH=$PATH:/usr/local/sbin/mypath
保存關閉文件後,如果要立即實現,則輸入:

source $HOME/.bash_profile
或者

. $HOME/.bash_profile
最後,驗證一下:

echo $PATH
樣例輸出:

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/sbin/mypath
方法2: /etc/paths.d 目錄

蘋果推薦使用path_helper工具生成PATH變量,一下是man的介紹:

The path_helper utility reads the contents of the files in the directories /etc/paths.d and /etc/manpaths.d and appends their contents to the PATH and MANPATH environment variables respectively.

(The MANPATH environment variable will not be modified unless it is already set in the environment.)

Files in these directories should contain one path element per line.

Prior to reading these directories, default PATH and MANPATH values are obtained from the files /etc/paths and /etc/manpaths respectively.

列出已存在的path,輸入:

ls -l /etc/paths.d/
樣例輸出:

total 16
-rw-r--r-- 1 root wheel 13 Sep 28 2012 40-XQuartz
你可以使用cat命令看一下40-XQuartz的path設置

cat /etc/paths.d/40-XQuartz
樣例輸出

/opt/X11/bin
把/usr/local/bin/mypath設置進$PATH,輸入:

sudo -s 'echo "/usr/local/sbin/mypath" > /etc/paths.d/mypath'
或者使用像下面一樣使用vi指令創建/etc/paths.d/mypath文件:

sudo vi /etc/paths.d/mypath
加入下面內容:

/usr/local/sbin/mypath
保存關閉文件後,你需要重啓系統,或者你可以重啓終端看一下改變。

結論

使用$HOME/.bash_profile僅生效於單個用戶。
使用etc/paths.d/使在這個系統上的所有用戶生效,但此方法僅在OS X Leopard或者更高的系統上生效。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章