views:

87

answers:

3

So, let's say that I have a command, foo, in a script which has both a return value, and an output string that I'm interested in, and I want to store those into a variable (well at least its output for the variable, and its return value could be used for a conditional).

For example:

a=$(`foo`)   # this stores the output of "foo"
if foo; then # this uses the return value
    stuff...
fi

The best thing that I could think of to capture that output is to use some temporary file:

if foo > $tmpfile; then
    a=$(`cat $tmpfile`)
    stuff...
fi

Is there anyway I could simplify that?

+4  A: 

this?

out=$(cmd)
rv=$?
if test $rv -eq 0; then
  echo "all good"
  echo $out
else
  echo "wtf, exit code was $rv"
fi

btw, $() and backticks are two syntaxes for the same effect, which means that you only want to write

$(`foo`)

if foo outputs a text of a command you want to execute again. like:

foo()
{
  echo echo date
}
$(foo)
$(`foo`)
just somebody
Yeah, you're right about the backticks thing. I'm not sure why I put those there.
supercheetah
thanks by the way
supercheetah
+3  A: 
output=`foo`
echo "Return: $?" # $? is the return code
scotchi
+1  A: 

From bash: (note the first $ in the first column is my prompt)

$ A=$(echo abc; false); echo status:$? A:$A
status:1 A:abc

Don't use $() plus backticks, as that actually executes the command and then executes its output.

See also:

Roger Pate