How to call a C program in the bash script and store its return value on a variable?

advertisements

I have bash script where I ask the user for some inputs, and then I want to call a C program a few times, and sum the return value. Please note that the main function inside my C program has some printf statements also, and it returns an integer value. Here is the part of my bash script:

 #!/bin/bash

encBER=0

// Some other code where I read the values from the user

for i in $frames;
do
    tempEncBER=$(./enc_ber $bytes $snr $modulation $channel $alamouti)
    encBER=$((encBER + tempEncBER))
done

echo "Total BER is:" $encBER

The point is that I ask it to execute 10 times, meaning the frames variables has the value of 10, but it executes once, it shows some syntax error, and then executes again, and for the final result, the value of encBER is 0. It simply doesn't store anything there. How can I get the value of the return statement in my main function in my C program and use it in bash?


The return value of a program is store in the $? variable. So you only need to add each $?:

for i in $frames;
do
    ./enc_ber $bytes $snr $modulation $channel $alamouti
    encBER=$((encBER + $?))
done

Note that the value is restricted to eight bits, so the maximum value is 255.


If you want to capture an integer greater than 255 or a float for instance, use stderr for all the things you don't want (fprintf(stderr, "Things I don't want\n");) and stdout to print the return value you want to catch.