什么是测试一个bash函数的返回值正确的方法? [英] What is proper way to test a bash function return value?
问题描述
我想,如果这样的语句在测试bash函数的返回值:
如果[FUNC参数]]。然后 …
但我得到错误信息,如:。预计有条件的二元运算
什么是做到这一点的正确方法?
它是:
如果[[$(FUNC ARG)];然后 ...
如果它退出code,而不是你可以只使用结果
如果FUNC ARG;然后 ...
如果你不能使该函数返回一个适当的退出code(带返回否
),你必须使用字符串的结果,使用@Alex Gitelman答案。
$帮助,如果
:
,如果:如果命令;然后命令; [ELIF命令;然后命令; ] ... [其他命令; ]网络
基于条件执行命令。
,将执行
如果有命令
列表。如果退出状态是零,那么
则执行的命令
列表。否则,每个的elif COMMANDS
列表
反过来执行,如果它的退出状态是0,则相应的
则执行的命令
列表以及如果命令完成。除此以外,
执行`别人COMMANDS列表中,如果present。的退出状态
整个结构是最后执行的命令的退出状态,或零
如果所有条件都不满足。
退出状态:
返回最后执行的命令的状态。
块引用>I would like to test a bash function return value in an if statement like this:
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 ...
解决方案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.
$ help if
:
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
Execute commands based on conditional.
The
if COMMANDS
list is executed. If its exit status is zero, then thethen COMMANDS
list is executed. Otherwise, eachelif COMMANDS
list is executed in turn, and if its exit status is zero, the correspondingthen COMMANDS
list is executed and the if command completes. Otherwise, the `else COMMANDS' list 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.
这篇关于什么是测试一个bash函数的返回值正确的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!