开发者

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

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 t开发者_开发知识库here anyway I could simplify that?


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


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:

  • bash manual
  • Unix shell quote tutorial
  • http://mywiki.wooledge.org/BashFAQ
  • http://mywiki.wooledge.org/BashGuide
  • http://bash-hackers.org/wiki/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜