現在演示如何用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
- }
有了這個,以後工作就方便多了。