在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Shell函数返回值,一般有3种方式:return,argv,echo 1) 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 0 mytest 2 mytest 1 = arg1 = 1 mytest 0 = arg1 = 0 if fasle arg1 = 1 arg1 = 0 end 先定义了一个函数mytest,根据它输入的参数是否为1来return 1或者return 0. 2) argv全局变量 #!/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" 结果: 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 文件中的内容如下: yxb g_var= 3) echo 返回值 #!/bin/bash ############################################## # Author : IT-Homer # Date : 2012-09-06 # Blog : http://blog.csdn.net/sunboy_2050 ############################################## function mytest5() { grep "123" test.txt | awk -F: '{print $2}' | while read line; do if [ $line = "yxb" ]; then echo "0" # value returned first by this function return 0 fi done return 1 } echo '$? = '"$?" result=$(mytest5) echo "result = $result" echo if [ -z $result ] # string is null then echo "no yxb. result is empyt" else echo "have yxb, result is $result" fi 结果: have yxb, result is 0 |
请发表评论