简体   繁体   English

有没有一种方法可以捕获命令的输出,并将其返回值转换为Shell脚本中的变量?

[英]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). 因此,假设我在脚本中有一个命令foo ,该脚本既有返回值,也有我感兴趣的输出字符串,我想将它们存储到变量中(至少是它的输出用于变量,其返回值可用于条件)。

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? 无论如何,我可以简化一下吗?

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. 如果foo输出您要再次执行的命令的文本。 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) 从bash:(请注意第一栏中的第一个$是我的提示)

$ 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: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM