测试 bash 函数返回值的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6241256/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:36:30  来源:igfitidea点击:

What is proper way to test a bash function return value?

bashfunction

提问by grok12

I would like to test a bash function return value in an if statement like this:

我想在这样的 if 语句中测试 bash 函数的返回值:

if [[ func arg ]] ; then …

but I get error messages like: conditional binary operator expected.

但我收到错误消息,如:预期条件二元运算符。

What is the right way to do this?

这样做的正确方法是什么?

Is it:

是吗:

 if [[ $(func arg) ]] ; then ...

回答by kay - SE is evil

If it was the exit code and not the result you could just use

如果是退出代码而不是结果,您可以使用

if func arg; then ...

If you cannot make the function return a proper exit code (with return N), and you have to use string results, use @Alex Gitelman answer.

如果您无法使函数返回正确的退出代码(使用return N),并且您必须使用字符串结果,请使用 @Alex Gitelman 答案。

$ help if:

$ help if

if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi

Execute commands based on conditional.

The if COMMANDSlist is executed. If its exit status is zero, then the then COMMANDSlist is executed. Otherwise, each elif COMMANDSlist is executed in turn, and if its exit status is zero, the corresponding then COMMANDSlist is executed and the if command completes. Otherwise, the else COMMANDSlist is executed, if present. The exit status of the entire construct is the exit status of the last command executed, or zero if no condition tested true.

Exit Status: Returns the status of the last command executed.

if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi

根据条件执行命令。

if COMMANDS执行列表。如果其退出状态为零,则 then COMMANDS执行列表。否则,elif COMMANDS依次执行每个列表,如果其退出状态为零,then COMMANDS则执行相应的 列表并完成 if 命令。否则,else COMMANDS执行列表(如果存在)。整个构造的退出状态是最后执行的命令的退出状态,如果没有条件测试为真,则为零。

退出状态:返回最后执行的命令的状态。

回答by Pedro Inácio

This was useful for me, so I would add the following details.

这对我很有用,所以我会添加以下详细信息。

If you need to test two conditions, one being the exit status of function/command and the other e.g. value of variable use this:

如果您需要测试两个条件,一个是函数/命令的退出状态,另一个是变量的值,请使用:

if func arg && [[ $foo -eq 1 ]]; then echo TRUE; else echo FALSE; fi

回答by Alex Gitelman

This error seems to be produced if function returns more than one word.

如果函数返回多个单词,似乎会产生此错误。

For example, 1 2.

例如,1 2

Just quote it:

简单引用一下:

"$(func arg)"

Sample:

样本:

$ if [[ 1 2 ]] ; then echo 1 ; fi
-bash: conditional binary operator expected
-bash: syntax error near `2'
$ if [[ "1 2" ]] ; then echo 1 ; fi
1


And if you compare 0 vs non 0 just use

如果您比较 0 与非 0,只需使用

if [[ "$(func arg)" != "0" ]]