现在演示如何用bash脚本自动化部署JDK。
环境:Ubuntu12.04 amd 64 Desktop or Server, 必须是Bash shell
复制目录Java到目标机器,用root权限执行install.sh脚本即可。
看一下目录结构:
. ├── check.sh ├── install.sh ├── jdk1.6.0_35 ├── readme └── tool.sh
要执行的就是install.sh,这个脚本会先调用check.sh脚本里的函数判断当前是否安装了jdk,版本号是否是1.6.0_35. 如果没有安装或者版本号不同,就安装。jdk1.6.0_35目录是解压后的oralce的Linux 64位的jdk包
tool.sh提供了基本的一些复制目录和创建软链接的函数。
先看install.sh脚本:
#!/bin/bash source check.sh source tool.sh hasJava r=$? SRC_JDK_FILES=./jdk1.6.0_35 DST_JDK_FILES=/usr/jdk1.6.0_35 if [ $r -eq 1 ] then echo "java was installed" else echo "java was not installed" copyFolder $SRC_JDK_FILES $DST_JDK_FILES createLink $DST_JDK_FILES /usr/jdk1.6 createLink '/usr/jdk1.6/bin/java' '/etc/alternatives/java' createLink /etc/alternatives/java /usr/bin/java fi
再看check.sh脚本#!/bin/bash #check java is available in this session function hasJava { v=`java -version 2>&1` echo 'check java platform...' pos=`expr match "$v" 'java version \"1.6.0_35\"'` if [ $pos -gt 0 ] then return 1 else return 0 fi }
最后再看tool.sh脚本#!/bin/bash function copyFolder { if [ -d "$2" ] then echo "$2 folder exists already, stop copying." else echo "$2 folder doesn't exists, start copying..." cp -r $1 $2 fi } #create a link($2) to file($1) function createLink { if [ -f "$2" ] then echo "$2 link exists already, removing it..." rm $2 else echo "$2 link doesn't exists, creating it..." fi echo "creating link: $2 to $1" ln -s $1 $2 }
有了这个,以后工作就方便多了。