在bash脚本返回值 [英] Return value in bash script
问题描述
我有一个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有一个收益
语句,你可以用它指定的唯一的事情是函数自身的退出
状态(0和255之间的值,0表示成功)。因此,收益
是不是你想要的。
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.
下面是一个例子:
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 || FUN2
如果FUN1返回一个0值将只运行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 0 value. The default return value is the last statement executed within the function.
这篇关于在bash脚本返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!