將前面的檢查java代碼封裝為函數。
相關閱讀:bash 腳本編程八 匹配命令輸出 http://www.linuxidc.com/Linux/2012-09/70737.htm
然後再調用之,腳本修改如下:
- #!/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'`
- if [ $pos -gt 0 ]
- then
- return 1
- else
- return 0
- fi
- }
-
- hasJava
- r=$?
-
- echo $r
-
- if [ $r -eq 1 ]
- then
- echo "java was installed"
- else
- echo "java was not installed"
- fi
運行結果:
- $ ./install.sh
- check java platform...
- 1
- java was installed
注意:
r=$?是獲得函數執行返回結果的方法。