0

I'd like to compile and run a C++ program via Bash and then capture the output produced by cout (which will be a int) to a variable in the Bash script.

I'm currently able to direct the output to a text file like so:

./prog >> output.txt

My research has led me to this, which appears to be creating an empty string:

output=$(./prog) | bc -l

In case it's relevant, I'm trying to capture this value so that I can average the output of my program over multiple executions. Here's my entire script as it currently stands:

count=1
while [ $count -le 8192 ]
do
    sum=0
    arraysize=$(( $count * 1024 ))
    g++-7 prog.cpp -DGLOBAL=${arraysize} -DLOCAL=32 -o prog -lm -fopenmp -framework OpenCL
    for try in {0..9}
    do
        output=$(./prog) | bc -l
        echo ${output} # this line appears to print an empty string
        sum=$(( (sum + output) ))
    done
    echo ${sum / 10}
    count=$(( $count * 2 ))
done

I know that there are likely other errors in the script above, but the one that's currently hanging me up is just capturing the value produced by the program.

8
  • 1
    What does the output look like? Commented Jun 1, 2018 at 1:02
  • Ten blank lines. Commented Jun 1, 2018 at 1:02
  • I'm meaning from ./prog >> output.txt... Commented Jun 1, 2018 at 1:03
  • 1
    Why are you piping to bc? Maybe try to move that into the parenthesis, if you actually want to capture the output bc gives for the output of your program. Commented Jun 1, 2018 at 1:05
  • 1
    @AlexJohnson Anything that looks like a number will be treated as a number. You can also use typeset -i output to declare the variable to hold an integer. Commented Jun 1, 2018 at 1:44

2 Answers 2

4

Here is what could help:

var=$(./prog)
Sign up to request clarification or add additional context in comments.

Comments

3

There's more than one way, but one is to use the backtick character:

VAR=`./prog`

2 Comments

This (and $(...), for the record) appear to have solved my problem. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.