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.
The output from a program is different from its return code. The return code should generally be 0, indicating success, or non zero, indicating failure. If you want the return code then you can simply run the program and check the variable $? afterwards:
./enc_ber $bytes $snr $modulation $channel $alamouti
retVal=$?
# retVal now contains the value passed back from the exit of your program.
Be careful not to do anything in between running your program and checking the result otherwise the value of $? will change again.
On the other hand, if you want your program to write a value to stdout and that's the output you need to obtain then you'll have to redirect the output to a file and then read the content of file:
./enc_ber $bytes $snr $modulation $channel $alamouti >./my_file.txt
output=$( cat my_file.txt )
# output now contains whatever enc_ber wrote to stdio
Naturally, you program will have to write only those things you wish to capture. Log lines and other extra formatting will cause you problems. The above is a simple example - it's up to you to parse whatever your program outputs, but the above should work for a simple number output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With