tags:

views:

392

answers:

4

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  A: 
Dev er dev
It works. I'll hold out for a slightly more elegant solution--otherwise you've got it.
Adam Ernst
+5  A: 
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.

ephemient
+2  A: 
var=`svn ls` && export var
jmohr
A: 
export FOO=$(your-command) || echo "your-command failed"
Jeremy Cantrell
This doesn't work, as the question states: $? gets set from "export", not "your-command", if you write it like this.
ephemient