Bash shell脚本:如何设置JAVA_HOME环境变量

时间:2011-03-25 19:31:12

标签: java bash environment-variables

使用openSUSE,我下载了适用于jdk1.6.0_24的Oracle rpms,我想将java home环境变量设置为/usr/java/jdk1.6.0_24但是/ etc / alternatives系统无法自动检测到这个安装JDK。更新替代品,或任何找不到jdk的东西。

所以,我想在BASH脚本中手动检测JAVA home。

如果我运行此命令:sudo find / usr -name'jdk1.6 *',我得到这个结果:

/usr/java/jdk1.6.0_24

如何将管道导入环境变量?我想做像

这样的事情
#!/bin/bash
read in JAVA_HOME var from a file
if file doesnt exist
  sudo find /usr -name 'jdk1.6*' 
  prompt user for which jdk is correct
  set that choice to a variable 
  add the JDK to alternatives if it is missing
  save variable to a file and dont prompt next time
  set the alternatives java choice
fi
echo $JAVA_HOME

4 个答案:

答案 0 :(得分:4)

类似

#!/bin/bash
function validate_java_home {
    if [ -z ${JAVA_HOME} ]
    then
        # do something if the file doesn't provide ${JAVA_HOME}
    else 
        if [ ! -e ${JAVA_HOME} ]
        then
            # do something if the file provides a non existent ${JAVA_HOME}
        fi
    fi
}

if [ ! -e ${YOUR_FILE_NAME_CONTAINING_JAVA_HOME} ]
then
     JAVA_HOME_CANDIDATES=$(find /usr -name 'jdk1.6*')
     echo "Found the following candidates for JAVA_HOME, reply with the one you want then press return"
     echo ""
     echo $JAVA_HOME_CANDIDATES
     read USER_SUBMITTED_JAVA_HOME
     echo "You chose $USER_SUBMITTED_JAVA_HOME"
     JAVA_HOME=${USER_SUBMITTED_JAVA_HOME}
else
    . ${YOUR_FILE_NAME_CONTAINING_JAVA_HOME}
fi 
validate_java_home
export ${JAVA_HOME}

我没有测试过,但希望你能得到一个要点(我会说使用select作为格伦杰克曼的答案更简洁/友好,不知道存在,所以我很高兴我读了这个Q! )

答案 1 :(得分:4)

oldIFS="$IFS"
IFS=$'\n'
choices=( $(find /usr/java -type d -maxdepth 1 -print) )
select choice in "${choices[@]}"; do
  [[ "$choice" ]] && break
done
IFS="$oldIFS"
export JAVA_HOME="$choice"

答案 2 :(得分:2)

不是坐在Linux终端上,但这应该让你开始:

...
jdkpath=`sudo find /usr -name 'jdk1.6*'`
export JAVA_HOME=$jdkpath
...

根据需要进行调整。

答案 3 :(得分:0)

根据Matt的回答,这是我正在使用的脚本:

#!/bin/bash
# JAVA_HOME script for RPM based java installations
# http://www.oracle.com/technetwork/java/javase/install-linux-64-rpm-138254.html
# examine and understand /etc/alternatives before you run this

cd $SITE_HOME

function set_java_home {
  if [ -z $JAVA_HOME ]; then
      echo "Using default value for JAVA_HOME: /usr/java/default"
      JAVA_HOME=/usr/java/default
  fi
  export -p JAVA_HOME
  echo $JAVA_HOME > java.home.config
  echo "JAVA_HOME variable set to $JAVA_HOME ."
}

if [ -f java.home.config ]; then
  JAVA_HOME=$(<java.home.config)
else
  JAVA_HOME_CANDIDATES=$(find /usr -type d -name 'jdk1.6*')
  echo "Found the following candidates for JAVA_HOME. Pick one: "
  echo "---"
  echo $JAVA_HOME_CANDIDATES
  echo "---"
  read USER_SUBMITTED_JAVA_HOME
  echo "You chose $USER_SUBMITTED_JAVA_HOME ."
  JAVA_HOME=${USER_SUBMITTED_JAVA_HOME}
fi
# Set the variable
set_java_home