可以將前面的環境變量設置代碼封裝成函數,
bash 腳本編程十二 環境變量的設置 http://www.linuxidc.com/Linux/2012-09/70733.htm
相關閱讀:bash 腳本編程
以後可以反復使用:
- # $1 variable name
- # $2 expected value
- # put this into /etc/environment if not found
- function setEnv {
- source /etc/environment
- if [ "${!1}" = "$2" ]
- then
- echo "$1 is correct: $2"
- else
- echo "$1 is wrong: ${!1} != $2"
-
- h=`grep "$1=\"$2\"" /etc/environment`
- if [ -n "$h" ]
- then
- echo "/etc/environment has $1 already"
- else
- echo "Adding $1 into /etc/environment..."
- echo "$1=\"$2\"" >> /etc/environment
- fi
- source /etc/environment
- fi
- }
調用方法:
- setEnv "JAVA_HOME" "/usr/jdk1.6"
說明:
1.$1 是 取第一個參數
2.如果第一個參數是JAVA_HOME, 代碼中 需要變成 $JAVA_HOME,然後再取其值
要用${!1}
3.為了防止函數運行前environment文件被修改過,所以主動執行source命令