1

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?

3 Answers 3

4

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`)
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, you're right about the backticks thing. I'm not sure why I put those there.
3
output=`foo`
echo "Return: $?" # $? is the return code

Comments

2

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.