bash - 调用函数直接返回返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11032902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash - Directly returning the return value from calling a function
提问by helpermethod
In bash, how can I directly return the return value returned by calling a function (sry, I don't know how to express this better). Example:
在bash中,如何直接返回调用函数返回的返回值(sry,我不知道如何表达更好)。例子:
foo() {
echo ""
return 1
}
bar() {
return foo 1
}
bar
If I do this, bash complains that a numeric parameter for the return statement is needed.
如果我这样做,bash 会抱怨 return 语句需要一个数字参数。
EDIT
编辑
I updated my example to better express the real problem. No only do I want to return the return code, I also want to pass a value to the function first... not sure if this is actually doable.
我更新了我的例子以更好地表达真正的问题。我不仅想返回返回码,我还想先将一个值传递给函数……不确定这是否真的可行。
采纳答案by Paused until further notice.
In these modifications of your example, I change the argument to footo make it easier to distinguish the result of one from the other.
在您的示例的这些修改中,我将参数更改为foo,以便更容易区分一个结果和另一个结果。
foo() {
echo ""
return 1
}
bar() {
return "$(foo 2)"
}
bar
echo "$?"
The preceding will output "2". The echoin foois used as the return value of bar. The range of values that return(and exit) can handle is 0 to 255.
前面的将输出“2”。将echo在foo被用作返回值bar。return(和exit) 可以处理的值范围是 0 到 255。
foo() {
echo ""
return 1
}
bar() {
foo 2
return "$?"
}
bar
echo "$?"
The second version will first output 2 since that's what foodoes then a 1 will be output since that's the return value of barhaving been propagated from the return value of foo.
第二个版本将首先输出 2 因为那是什么foo然后将输出 1 因为这是bar从 的返回值传播的返回值foo。
回答by piokuc
The only thing you can return from a shell script or a shell function is a numeric error code.
您可以从 shell 脚本或 shell 函数返回的唯一内容是数字错误代码。
However, you can print some text to standard output in the function (or separate script, it's the same) using echo, cat, etc., and then capture the output, using bacticks syntax or $(...) syntax. Passing parameters to shell functions works the same way as passing parameters to scripts:
但是,您可以使用 echo、cat 等将一些文本打印到函数中的标准输出(或单独的脚本,它是相同的),然后使用 bacticks 语法或 $(...) 语法捕获输出。将参数传递给 shell 函数的工作方式与将参数传递给脚本的方式相同:
回答by Vijay
This should work: you can only return a number in bash.
这应该有效:您只能在 bash 中返回一个数字。
foo() {
return 1
}
bar() {
foo
return 1
}
bar
回答by Wieland
You can simply return the return code of the last call $?:
您可以简单地返回上次调用 $? 的返回码:
foo() {
echo ""
return 1
}
bar() {
foo "bla"
return $?
}
bar

