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

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

#!/bin/bash

function func1(){
  count=0
  for cont in {1..3}; do
    count=`expr $count + 1`
  done
  # 函数中使用return返回时,返回值的数据类型必须是数字
  return $count
}

# 在$()的圆括号中可以执行linux命令,当然也包括执行函数
res1=$(func1)

# 变量res2将会接收函数的返回值,这里是3
res2=`echo $?`

if [[ $res2 == 3 ]]; then
  echo "func1() succeeded!"
else
  echo "Not a right number!"
fi

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

func1() succeeded!

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

#!/bin/bash

# 也可在函数中使用echo作返回值
function func2(){
  first_name=$1
  middle_name=$2
  family_name=$3
  echo $first_name
  echo $middle_name
  echo $family_name
}

# 使用$(func_name arg1 arg2 ...)来获取函数中所有的echo值
res3=$(func2 "tony" "kid"   "leung")
echo "func2 'tony' 'kid'  'leung' RESULT IS____"$res3

res4=$(func2 'who' 'is' 'the' 'most' 'handsome' 'guy?')
echo "func2 'who' 'is' 'the' 'most' 'handsome' 'guy?' RESULT IS____"$res4

if [[ $res4 =~ "tony" ]]; then
  echo "it includes tony ^_^ "
else
  echo "Input name doesn't include 'tony'!"
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’!

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

猜你喜欢

转载自blog.csdn.net/qq_31598113/article/details/80611480
今日推荐