How to return program output to a variable?

Can someone tell me how to return the program output to a variable from the command line?

var = ./a.out params 

I am trying to get the output of a program into a variable during its launch from the command line.

+4
source share
4 answers

To complement the answer from rasen , in order to get a variable from your program into the external environment, you need to print it before stdout .

Using the syntax provided in another answer, it simply takes all the output from stdout and puts it in the var shell environment variable.

-1
source

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

 var=`./a.out params` 

or

 var=$(./a.out params) 

Remember that you should not put spaces before or after the = operator.

+9
source

To output from a 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" 
+1
source

You can transfer the value from your program to the shell via stdout (as already mentioned) or using the return in your main() function from your C program. Below is one liner that illustrates both approaches:

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

11

The variable a is printed on stdout , and the variable b returned in main() . Use $? in bash to get the return value of the most recently invoked command (in this case ./a.out ).

0
source

Source: https://habr.com/ru/post/1489211/


All Articles