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 outp
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.
Using the syntax provided in the other answer simply takes all output from stdout and puts it in the shell environment variable var.
To save the program output to stdout in variable in Unix shell, regardless of language program wrote in, you can use something like this
var=`./a.out params`
or this
var=$(./a.out params)
Remember not to put spaces before or after the = operator.
You can pass value from your program to shell via stdout (as was already said) or using return statement in your main() function from your C program. One-liner below 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
Variable a is printed to stdout and variable b is returned in main(). Use $? in bash to get return value of most recent invoked command (in this case ./a.out).
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"