Bash 函数中的返回值 [英] Return value in a Bash function

查看:43
本文介绍了Bash 函数中的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个 bash 脚本,我想执行一个函数来打印返回值:

I am working with a bash script and I want to execute a function to print a return value:

function fun1(){
  return 34
}
function fun2(){
  local res=$(fun1)
  echo $res
}

当我执行 fun2 时,它不打印34".为什么会这样?

When I execute fun2, it does not print "34". Why is this the case?

推荐答案

虽然 Bash 有一个 return 语句,你唯一可以用它指定的是函数自己的 exit> 状态(0255 之间的值,0 表示成功").所以 return 不是你想要的.

Although Bash has a return statement, the only thing you can specify with it is the function's own exit status (a value between 0 and 255, 0 meaning "success"). So return is not what you want.

您可能希望将 return 语句转换为 echo 语句 - 这样就可以使用 $() 大括号捕获函数输出,这似乎正是您想要的.

You might want to convert your return statement to an echo statement - that way your function output could be captured using $() braces, which seems to be exactly what you want.

这是一个例子:

function fun1(){
  echo 34
}

function fun2(){
  local res=$(fun1)
  echo $res
}

另一种获取返回值的方法(如果您只想返回一个 0-255 的整数)是 $?.

Another way to get the return value (if you just want to return an integer 0-255) is $?.

function fun1(){
  return 34
}

function fun2(){
  fun1
  local res=$?
  echo $res
}

另外,注意你可以使用返回值来使用布尔逻辑——比如 fun1 ||如果 fun1 返回非 0 值,fun2 只会运行 fun2.默认返回值是函数内执行的最后一条语句的退出值.

Also, note that you can use the return value to use Boolean logic - like fun1 || fun2 will only run fun2 if fun1 returns a non-0 value. The default return value is the exit value of the last statement executed within the function.

这篇关于Bash 函数中的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆