bash 脚本编程九 函数

将前面的检查java代码封装为函数,然后再调用之,脚本修改如下:

#!/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=$?是获得函数执行返回结果的方法。






你可能感兴趣的:(bash,脚本,bash,编程,java)