首页 > 系统 > Linux > 正文

Linux Shell函数返回值

2019-10-26 18:49:26
字体:
来源:转载
供稿:网友

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 1echo $?     # print return resultecho echo "mytest 0"mytest 0echo $?     # print return resultecho echo "mytest 2"mytest 2echo $?     # print return resultechoecho "mytest 1 = "`mytest 1`if mytest 1 ; then  echo "mytest 1"fiechoecho "mytest 0 = "`mytest 0`if mytest 0 ; then  echo "mytest 0"fiechoecho "if fasle" # if 0 is errorif false; then  echo "mytest 0"fiechomytest 1res=`echo $?`  # get return resultif [ $res = "1" ]; then  echo "mytest 1"fiechomytest 0res=`echo $?`  # get return resultif [ $res = "0" ]; then  echo "mytest 0"fiecho 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 1echo "return $?"echoecho "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}mytest3echo $?echomytest4echo $?echoecho "g_var=$g_var"

其中,test.txt 文件中的内容如下:
456:kkk
123:yxb
123:test
结果:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表