Detecting failure of a Bash “export” value

江枫思渺然 提交于 2020-01-11 09:20:49

问题


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

export var=`svn ls`

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?


回答1:


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

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

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

var=`svn ls` && export var || 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.




回答2:


var=`svn ls` && export var



回答3:


I had similar problem, it can be done like this:

rm -f error_marker_file
export var=`svn ls || touch error_marker_file`

[ -f error_marker_file ] && echo "error in executing svn ls"



回答4:


export FOO=$(your-command) || echo "your-command failed"


来源:https://stackoverflow.com/questions/247706/detecting-failure-of-a-bash-export-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!