linux shell返回值方式及示例

来源:互联网 发布:sql多张表合并 编辑:程序博客网 时间:2024/05/16 15:48

概述

  Shell函数返回值,常用的两种方式:echo和return

echo

据man手册描述:echo是一个输出参数,有空格分割,会产生一个新行。返回永远是0。

echo一般起到一个提示的作用。在shell编程中极为常用, 在终端下打印变量value的时候也是常常用到的。

在shell中子进程会继承父进程的标准输出,因此,子进程的输出也就直接反应到父进程。所以函数的返回值通过输出到标准输出是一个非常安全的返回方式。

使用echo返回的示例

[root@wmstianjin16172 ~]# cat echoTestFun.sh #!/bin/bash  function echoTestFun()  {      if [ -z $1 ]     then          echo "0"      else          echo "$@"      fi  }echo "Agrs not null start:"echoTestFun $@  echo "Agrs not null end"echo "Agrs  null start:"echoTestFun  echo "Agrs  null end"

执行

[root@wmstianjin16172 ~]# ./echoTestFun.sh 1 hh 3Agrs not null start:1 hh 3Agrs not null endAgrs  null start:0Agrs  null end

return

shell函数的返回值,可以和其他语言的返回值一样,通过return语句返回,BUT return只能用来返回整数值;且和c的区别是返回为正确,其他的值为错误。

使用return返回的示例

[root@wmstianjin16172 ~]# cat returnTestFun.sh #!/bin/bash  function returnTestFun()  {      if [ -z $1 ]    then          return 0      else          return 1      fi  }echo "Agrs not null start:"returnTestFun $@  echo $?echo "Agrs not null end"echo "Agrs  null start:"returnTestFunecho $?echo "Agrs  null end"

执行

[root@wmstianjin16172 ~]# ./returnTestFun.sh hello worldAgrs not null start:1Agrs not null endAgrs  null start:0Agrs  null end

若返回不是整数的返回值,将会得到一个错误
如把上例中的return 1改为return $1,使用同样的参数运行将得到提示:

./returnTestFun.sh: line 8: return: hello: numeric argument required
原创粉丝点击