Kian Cross
Kian Cross

Reputation: 1818

How can I return a value from a c program to the back script that calls it?

I'm trying to solve a problem where I want a bash script to call a c program and a value from the c program to be returned to the bach script and be stored in a variable.

Here is an example (code isn't really written properly):

Bash script:

$value = ./foo
echo $value

C program:

int main() {
    //Have a value here that is returned to the variable 'value' in the bash script.
    return 0;
}

Is this possible?

Upvotes: 0

Views: 94

Answers (3)

pmg
pmg

Reputation: 108978

To have you script echo the value returned from your C application, do

echo $?

Not a C question though

Upvotes: 0

Cyrus
Cyrus

Reputation: 88583

Print the value to stdout in your c program:

printf("%s",value);

or

printf("%s\n",value);

Your bash script:

#!/bin/bash

value="$(your_c_program)"
echo "$value"

Upvotes: 1

Alex Díaz
Alex Díaz

Reputation: 2363

You can get the return value of the last program you executed by using $? or you can print the value to stdout and then capture it.

#include <stdio.h>

int main()
{
    printf("my_value");
    return 0;
}

and then in bash do

value=$(./my_program)
echo $value

the result will be my_value

Upvotes: 1

Related Questions