Sonu Mishra Sonu Mishra - 4 months ago 10
Bash Question

Taking the return value of a process in shell script

I have a C program, say

hello_world
. The main function returns an
int
. 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.

/*hello_world.c*/
#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


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


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

Answer

It's quite a simple thing to do

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

But if you want to capture the OUTPUT of the program

output=$(hello_world 31)

or

output=`hello_world 31`