shell脚本 之 函数返回值

转载地址:https://inter12.iteye.com/blog/1236399

shell 函数返回值

只允许返回数字,若不是则报 line 6: return: haha: numeric argument required

若是写了return ,则返回return 语句跟的数值,若是没有return语句则返回最后一个命令的执行结果。

用例子说话吧

  1 #!/bin/bash

  2 

  3 returnNum(){

  4       return 10

  5 }

  6 

  7 returnLasCommand(){

  8       pwd

  9 }

 10 

 11 returnString=""

 12 

 13 returnString(){

 14     returnString="haha"

 15 }

 16 

 17 returnString1(){

 18     return "haha"

 19 }

 20 

 21 r1=$(returnNum)

 22 echo 'r1' $?

 23 

 24 r2=$(returnLasCommand)

 25 echo 'r2' $?

 26 

 27 returnString

 28 echo 'r3' $returnString

 29 

 30 returnString1

 -----------------------------

inter12@inter12:~/myshell/shell/declare$ ./mm2 

r1 10

r2 0

r3 haha

./mm2: line 18: return: haha: numeric argument required

可以看到返回字符串的时候报错了!若是我们需要返回一个字符串怎么半呢?那只能实用全局变量的方式了!就是r3的方式

猜你喜欢

转载自blog.csdn.net/kunkliu/article/details/86536420