How to return the output of program in a variable?

后端 未结 4 420
轮回少年
轮回少年 2021-01-03 05:14

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

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-03 06:02

    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 \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).

提交回复
热议问题