Is there a way to capture the output of a command, and its return value into variables in a shell script?

StackOverflow https://stackoverflow.com/questions/1746273

  •  20-09-2019
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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`)

OTHER TIPS

output=`foo`
echo "Return: $?" # $? is the return code

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:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top