检测到Bash“导出"失败.价值 [英] Detecting failure of a Bash "export" value

查看:65
本文介绍了检测到Bash“导出"失败.价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Bash中,我正在执行命令,并将结果放入这样的变量中:

In Bash I'm executing a command and putting the result in a variable like this:

export var=`svn ls`

但是,如果SVN由于某种原因失败(例如,它返回了非零的错误代码),则export仍返回状态代码0.如何检测执行的命令是否失败?

But if SVN fails for some reason--say it returns a non-zero error code--export still returns status code 0. How do I detect if the executed command fails?

推荐答案

var=`svn ls`
if [[ $? == 0 ]]
then
        export var
else
        unset var
fi

$?是最后执行的命令的退出代码,此处为svn ls.

$? is the exit code of the last command executed, which is svn ls here.

jmohr的解决方案简短而甜美.适度地适应了

jmohr's solution is short and sweet. Adapted mildly,

var=`svn ls` && export var || unset var

大约等同于上述内容(有效标识符的export永远不会失败,除非您做了可怕的事情并且用尽了环境空间).随便随便便便-我使用unset只是为了避免$var即使没有导出也可能有值.

would be approximately equivalent to the above (export of a valid identifier will never fail, unless you've done something horrible and run out of environment space). Take whatever you want -- I use unset just to avoid $var possibly having a value even though it's not exported.

这篇关于检测到Bash“导出"失败.价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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