测试bash函数返回值的正确方法是什么? [英] What is the proper way to test a bash function return value?

查看:81
本文介绍了测试bash函数返回值的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

if [[ func arg ]] ; then …

但是我收到如下错误消息:conditional binary operator expected.

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

正确的方法是什么?

是吗

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

推荐答案

如果这是退出代码,而不是结果,则只能使用

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

if func arg; then ...

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

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

根据条件执行命令.

执行if COMMANDS列表.如果其退出状态为零,则 then COMMANDS列表被执行.否则,每个elif COMMANDS列表为 依次执行,如果其退出状态为零,则对应的 then COMMANDS列表已执行,并且if命令完成.否则, else COMMANDS列表(如果存在)将被执行.的退出状态 整个构造是最后执行的命令的退出状态,或者为零 如果没有条件被证明为真.

The if COMMANDS list is executed. If its exit status is zero, then the then COMMANDS list is executed. Otherwise, each elif COMMANDS list is executed in turn, and if its exit status is zero, the corresponding then 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆