Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

382
Views
Returning values from a C++ program into a bash script

I have a C++ program (on Linux) that computes a double result, and I want to write a bash script that runs the program a variable number of times and averages these results for me. For simplicity, consider the following code:

main.cpp:

int main() {
    cout << "Some other stuff\n";

    double result = foo();

    return 0;
}

script.sh:

sum = 0
num = $1
for((i = 0; i < $num; i++)); do
    result = ./a.out;  #store the result somehow?
    sum = $sum + $result
done
avg = $sum / $num
echo "Average: " $avg

Is there an easy way to pass the result of the program back into the bash script? I read about using the exit code, but the return type is a double so I don't think that will work. Parsing the value from string output is unwieldy because the program has other terminal output.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

The UNIX way of doing this is writing non-essential data on stderr and writing the actual result on stdout. That way, you can simply do

int main() {
    cerr << "This is output that won't be captured." << endl;
    cout << "3.141592" << endl; 
}

and use command substitution to capture it:

result=$(./a.out)

An uglier way of doing that doesn't require changing the output is to write to another file descriptor:

int main() { 
    char* foo = "3.141592\n";
    write(42, foo, strlen(foo));
}

This will let you capture the output with:

result=$(./a.out 42>&1 > /dev/null)

Note that your shell script has several syntax errors. Try shellcheck to automatically sort out many of them, and feel free to post a question about the issues you can't resolve.

over 4 years ago · Santiago Trujillo Report

0

Why don't you use return value as data to your bash script?

int main() {
        return 46;
}

The output is as follows (yes, it's bash script):

./a.out ; echo $?
46

In case of double values you could use this approach:

#include <iostream>

int main() {
        double res = 46.001;
        std::cout << res << std::endl;
        return 0;
}

And the output:

a=`./a.out`; echo $a
46.001
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!