以后可以反复使用:
# $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命令