How to return the output of program in a variable?

后端 未结 4 388
轮回少年
轮回少年 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 05:56

    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.

    0 讨论(0)
  • 2021-01-03 05:56

    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.

    0 讨论(0)
  • 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 <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).

    0 讨论(0)
  • 2021-01-03 06:09

    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"
    
    0 讨论(0)
提交回复
热议问题