乌班图多jdk环境切换

安装多个jdk环境
sudo apt install openjdk-8-jdk
sudo apt install openjdk-11-jdk
指令切换
sudo update-alternatives --config java
环境配置
export JAVA_HOME=$(update-alternatives --config java | grep "selected" | sed -E 's/.*\(selected\).*\/([^ ]+) .*/\1/') >> ~/.bashrc
export PATH=$JAVA_HOME/bin:$PATH >> ~/.bashrc
环境验证
source ~/.bashrc
echo $JAVA_HOME
java -version
自动化脚本
#!/bin/bash

# Determine the JAVA_HOME path based on the JDK version
set_java_home() {
  JAVA_VERSION=$1
  case $JAVA_VERSION in
    8)
      JAVA_HOME_PATH=/usr/lib/jvm/java-8-openjdk-amd64/jre
      ;;
    11)
      JAVA_HOME_PATH=/usr/lib/jvm/java-11-openjdk-amd64
      ;;
    *)
      echo "Usage: $0 {8|11}"
      exit 1
      ;;
  esac

  # Check if JAVA_HOME is already set in .bashrc
  if grep -q "export JAVA_HOME" ~/.bashrc; then
    # If found, update the JAVA_HOME value
    sed -i "s|export JAVA_HOME=.*|export JAVA_HOME=$JAVA_HOME_PATH|" ~/.bashrc
  else
    # If not found, add the JAVA_HOME to .bashrc
    echo "export JAVA_HOME=$JAVA_HOME_PATH" >> ~/.bashrc
    echo "export PATH=\$JAVA_HOME/bin:\$PATH" >> ~/.bashrc
  fi

  # Set the alternative for java
  sudo update-alternatives --set java $JAVA_HOME_PATH/bin/java

  echo "Switched to Java $JAVA_VERSION before:JAVA_HOME:$JAVA_HOME"
  java -version

  echo $SHELL

  # Apply changes
  /bin/bash -c "source ~/.bashrc"


  echo "Switched to Java $JAVA_HOME_PATH end:JAVA_HOME:$JAVA_HOME"
}

# Call the function with the first argument
set_java_home $1
posted @ 2024-12-09 15:56  懒懒初阳  阅读(3)  评论(0编辑  收藏  举报