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

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

问题描述

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

当我执行 fun2 时,它不打印34。为什么会出现这种情况?

解决方案

尽管bash有一个 return 语句,你可以指定的唯一的东西就是函数自己的 exit status(一个介于 0 和<$ c之间的值$ c> 255 ,0表示成功)。所以 return 不是您想要的。



您可能想将 return 语句添加到 echo 语句 - 这样,您的函数输出可以使用 $()大括号,这似乎正是你想要的。



下面是一个例子:

 < $ c $ func(){
echo 34
}

函数fun2(){
local res = $(fun1)
echo $ res

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

 函数fun1 ){
return 34
}

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

另外请注意,您可以使用return值使用布尔逻辑,如 fun1 ||如果 fun1 返回一个 0 将只运行 fun2 / code>值。默认返回值是在函数中执行的最后一条语句的退出值。


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
}

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

解决方案

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.

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.

Here is an example:

function fun1(){
  echo 34
}

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

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
}

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

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

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