shell脚本——如何获取函数的返回值

刺骨的言语ヽ痛彻心扉 2022-05-22 20:07 1643阅读 0赞

在shell脚本(以bash为例),既可以通过return关键字来返回函数的值,也可以通过echo关键字来返回函数的值。下面分开来讲一下如何捕获函数的返回值。
(1)函数中使用return返回函数值时,通过 echo $? 来捕获函数返回值。请看脚本 bash1.sh

  1. #!/bin/bash
  2. function func1(){
  3. count=0
  4. for cont in {
  5. 1..3}; do
  6. count=`expr $count + 1`
  7. done
  8. # 函数中使用return返回时,返回值的数据类型必须是数字
  9. return $count
  10. }
  11. # 在$()的圆括号中可以执行linux命令,当然也包括执行函数
  12. res1=$(func1)
  13. # 变量res2将会接收函数的返回值,这里是3
  14. res2=`echo $?`
  15. if [[ $res2 == 3 ]]; then
  16. echo "func1() succeeded!"
  17. else
  18. echo "Not a right number!"
  19. fi

$ ./bash1.sh # 运行此脚本,输出结果如下

func1() succeeded!

(2)函数中使用echo返回函数值时,通过 $(func_name arg1 arg2 …) 来捕获函数返回值,请看脚本bash2.sh

  1. #!/bin/bash
  2. # 也可在函数中使用echo作返回值
  3. function func2(){
  4. first_name=$1
  5. middle_name=$2
  6. family_name=$3
  7. echo $first_name
  8. echo $middle_name
  9. echo $family_name
  10. }
  11. # 使用$(func_name arg1 arg2 ...)来获取函数中所有的echo值
  12. res3=$(func2 "tony" "kid" "leung")
  13. echo "func2 'tony' 'kid' 'leung' RESULT IS____"$res3
  14. res4=$(func2 'who' 'is' 'the' 'most' 'handsome' 'guy?')
  15. echo "func2 'who' 'is' 'the' 'most' 'handsome' 'guy?' RESULT IS____"$res4
  16. if [[ $res4 =~ "tony" ]]; then
  17. echo "it includes tony ^_^ "
  18. else
  19. echo "Input name doesn't include 'tony'!"
  20. fi

$ ./bash2.sh # 运行此脚本,输出结果如下
func2 ‘tony’ ‘kid’ ‘leung’ RESULT IS____tony kid leung
func2 ‘who’ ‘is’ ‘the’ ‘most’ ‘handsome’ ‘guy?’ RESULT IS____who is the
Input name doesn’t include ‘tony’!

好了就写到这里,看官们觉得涨知识了,请在文章左侧点个赞 ^_^

发表评论

表情:
评论列表 (有 0 条评论,1643人围观)

还没有评论,来说两句吧...

相关阅读