在 bash 中,您可以使用函数调用作为 if 语句中的条件吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8117822/
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
In bash, can you use a function call as a condition in an if statement?
提问by chickeninabiscuit
here's what i'm trying to achive:
这就是我想要达到的目标:
function f1() {
return 0
}
function f2() {
return 0
}
if [[ f1 && f2 ]]; then
echo "success"
else
echo "fail"
fi
回答by Ignacio Vazquez-Abrams
You don't use [[
(or [
) when running a command and checking the result code.
在运行命令和检查结果代码时不要使用[[
(或[
)。
if f1 && f2 ; then
echo "success"
else
echo "fail"
fi
回答by evan
Yes. You can do this by checking against a return by means of echo (although not a strict return):
是的。您可以通过使用 echo 来检查返回(尽管不是严格返回)来做到这一点:
if [[ "$(f1)" == "whatever" ]]
works
if [[ "$(f1)" == "whatever" ]]
作品
See this page for more on function return values. It also has a couple of good comments specifically talking about if statements.
有关函数返回值的更多信息,请参阅此页面。它也有一些很好的评论,专门讨论 if 语句。
http://www.linuxjournal.com/content/return-values-bash-functions
http://www.linuxjournal.com/content/return-values-bash-functions