此脚本书写时仅为个人使用,如需使用可以修改,本篇内容为讲解需要修改的内容,完整脚本如下
#!/bin/bash
# 脚本存放位置 /opt/modules/
# 压缩包存放位置 /opt/modules/jdk-8u162-linux-x64.tar.gz
# 安装目录 /opt/installs
# 安装版本 jdk1.8.0_162
CRTDIR=$(pwd)
# 此处为压缩包存放位置
jdkTargz="/opt/modules/jdk-8u162-linux-x64.tar.gz"
echo "${jdkTargz}"
# 检查原先是否已配置java环境变量
checkExist(){
jdk1=$(grep -n "export JAVA_HOME=.*" /etc/profile | cut -f1 -d':')
if [ -n "$jdk1" ];then
echo "JAVA_HOME已配置,删除内容"
sed -i "${jdk1}d" /etc/profile
fi
jdk2=$(grep -n "export CLASSPATH=.*\$JAVA_HOME.*" /etc/profile | cut -f1 -d':')
if [ -n "$jdk2" ];then
echo "CLASSPATH路径已配置,删除内容"
sed -i "${jdk2}d" /etc/profile
fi
jdk3=$(grep -n "export PATH=.*\$JAVA_HOME.*" /etc/profile | cut -f1 -d':')
if [ -n "$jdk3" ];then
echo "PATH-JAVA路径已配置,删除内容"
sed -i "${jdk3}d" /etc/profile
fi
}
# 查询是否有jdk.tar.gz
if [ -e $jdkTargz ];
then
echo "— — 存在jdk压缩包 — —"
echo "正在解压jdk压缩包..."
tar -zxvf ${jdkTargz} -C /opt/installs
if [ -e "/opt/install/jdk" ];then
echo "存在/opt/install/jdk,删除..."
rm -rf /opt/install/jdk
fi
mv /opt/installs/jdk1.8.0_162 /opt/installs/jdk
# 检查配置信息
checkExist
echo "---------------------------------"
echo "正在配置jdk环境..."
sed -i '$a export JAVA_HOME=/opt/installs/jdk' /etc/profile
sed -i '$a export PATH=$PATH:$JAVA_HOME/bin' /etc/profile
echo "---------------------------------"
echo "JAVA环境配置已完成..."
echo "---------------------------------"
echo "正在重新加载配置文件..."
echo "---------------------------------"
source /etc/profile
echo "配置版本信息如下:"
java -version
else
echo "未检测到安装包,请将安装包放到/opt目录下"
fi