Sonu Mishra Sonu Mishra - 1 year ago 64
Bash Question

Taking the return value of a process in shell script

I have a C program, say

. The main function returns an
. Can I access and use this returned value in a shell script?

This is the C code. I have written a very simplified version of my program. The actual code is 1.2K lines.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
int i = 0;
if (argc == 2) {
i = atoi(argv[1]);
printf("Hello World - %d\n", i);
return 0;
else return -1;

This is the bash script to run the executable generated after compiling the above code. I am using GCC 4.1.2 and compiling using
gcc -o hello_world hello_world.c

ret=hello_world 31 # this gives a `command not found` error
if [ ret -eq 0 ]; then
echo "success"

Is there any way I can access the returned value from the script?

Answer Source

It's quite a simple thing to do

hello_world 31
if [ $? -eq 0 ];
    echo "success"

But if you want to capture the OUTPUT of the program

output=$(hello_world 31)


output=`hello_world 31`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download