Shell函数返回值,一般有3种方式:return,argv,echo
1) return 语句
shell函数的返回值,可以和其他语言的返回值一样,通过return语句返回。
示例:
#!/bin/bash -
function mytest()
{
echo "arg1 = $1"
if [ $1 = "1" ] ;then
return 1
else
return 0
fi
}
echo
echo "mytest 1"
mytest 1
echo $? # print return result
echo
echo "mytest 0"
mytest 0
echo $? # print return result
echo
echo "mytest 2"
mytest 2
echo $? # print return result
echo
echo "mytest 1 = "`mytest 1`
if mytest 1 ; then
echo "mytest 1"
fi
echo
echo "mytest 0 = "`mytest 0`
if mytest 0 ; then
echo "mytest 0"
fi
echo
echo "if fasle" # if 0 is error
if false; then
echo "mytest 0"
fi
echo
mytest 1
res=`echo $?` # get return result
if [ $res = "1" ]; then
echo "mytest 1"
fi
echo
mytest 0
res=`echo $?` # get return result
if [ $res = "0" ]; then
echo "mytest 0"
fi
echo
echo "end"
结果:
mytest 1
arg1 = 1
1
mytest 0
arg1 = 0
0
mytest 2
arg1 = 2
0
mytest 1 = arg1 = 1
arg1 = 1
mytest 0 = arg1 = 0
arg1 = 0
mytest 0
if fasle
arg1 = 1
mytest 1
arg1 = 0
mytest 0
end
先定义了一个函数mytest,根据它输入的参数是否为1来return 1或者return 0.
获取函数的返回值通过调用函数,或者最后执行的值获得。
另外,可以直接用函数的返回值用作if的判断。
注意:return只能用来返回整数值,且和c的区别是返回为正确,其他的值为错误。
2) argv全局变量
这种就类似于C语言中的全局变量(或环境变量)。
示例:
#!/bin/bash -
g_var=
function mytest2()
{
echo "mytest2"
echo "args $1"
g_var=$1
return 0
}
mytest2 1
echo "return $?"
echo
echo "g_var=$g_var"
结果:
mytest2
args 1
return 0
g_var=1
函数mytest2通过修改全局变量的值,来返回结果。
注: 以上两个方法失效的时候
以上介绍的这两种方法在一般情况下都是好使的,但也有例外。
示例:
#!/bin/bash -
function mytest3()
{
grep "123" test.txt | awk -F: '{print $2}' | while read line ;do
echo "$line"
if [ $line = "yxb" ]; then
return 0 # return to pipe only
fi
done
echo "mytest3 here "
return 1 # return to main process
}
g_var=
function mytest4()
{
grep "123" test.txt | awk -F: '{print $2}' | while read line ;do
echo "$line"
if [ $line = "yxb" ]; then
g_var=0
echo "g_var=0"
return 0 # return to pipe only
fi
done
echo "mytest4 here "
return 1
}
mytest3
echo $?
echo
mytest4
echo $?
echo
echo "g_var=$g_var"
其中,test.txt 文件中的内容如下:
456:kkk
123:yxb
123:test
结果:










