bash 如何在变量中返回程序的输出?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17418546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:49:06  来源:igfitidea点击:

How to return the output of program in a variable?

bash

提问by pkm

Can any one tell me how to return the output of a program in a variable from command line?

谁能告诉我如何从命令行以变量形式返回程序的输出?

var = ./a.out params

I am trying to get the output of program into a variable while running this from command line.

我试图在从命令行运行它时将程序的输出放入一个变量中。

采纳答案by Some programmer dude

To complement the answer from rasen, to get the variable from inside your program to the external environment, you need to print it to stdout.

为了补充rasen答案,要将变量从程序内部获取到外部环境,您需要将其打印到stdout.

Using the syntax provided in the other answer simply takes all output from stdoutand puts it in the shell environment variable var.

使用其他答案中提供的语法只需从stdoutshell 环境变量中获取所有输出并将其放入var

回答by Alexey Shmalko

To save the program output to stdoutin variable in Unix shell, regardless of language program wrote in, you can use something like this

要将程序输出保存到stdoutUnix shell 中的变量中,无论编写的语言程序如何,您都可以使用这样的东西

var=`./a.out params`

or this

或这个

var=$(./a.out params)

Remember not to put spaces before or after the =operator.

切记不要在=运算符之前或之后放置空格。

回答by Jahid

For output from multi-line command, you can do this:

对于多行命令的输出,您可以执行以下操作:

output=$(
#multiline multiple commands
)

Or:

或者:

output=$(bash <<EOF
#multiline multiple commands
EOF
)

Example:

例子:

#!/bin/bash
output="$(
./a.out params1
./a.out params2
echo etc..
)"
echo "$output"

回答by mzet

You can pass value from your program to shell via stdout(as was already said) or using returnstatement in your main()function from your C program. One-liner below illustrates both approaches:

您可以通过stdout(正如已经说过的)或return在您main()的 C 程序的函数中使用语句将值从您的程序传递到 shell 。下面的一行说明了这两种方法:

echo -e '#include <stdio.h>\n int main() { int a=11; int b=22; printf("%d\\n", a); return b; }' | gcc -xc -; w=$(./a.out); echo $?; echo $w

echo -e '#include <stdio.h>\n int main() { int a=11; int b=22; printf("%d\\n", a); return b; }' | gcc -xc -; w=$(./a.out); echo $?; echo $w

Output:

输出:

22

22

11

11

Variable ais printed to stdoutand variable bis returned in main(). Use $?in bash to get return value of most recent invoked command (in this case ./a.out).

变量a被打印到stdout并且变量b被返回到main(). $?在 bash 中使用以获取最近调用的命令的返回值(在本例中为./a.out)。