0

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?

Kian Cross
  • 1,818
  • 2
  • 21
  • 41
  • print the value to stdout and then capture it – Alex Díaz Aug 22 '15 at 20:18
  • So something like [this](http://stackoverflow.com/questions/4651437/how-to-set-a-bash-variable-equal-to-the-output-from-a-command)? If so, you'll want to use printf statements instead. – tonysdg Aug 22 '15 at 20:19

3 Answers3

1

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"
Cyrus
  • 84,225
  • 14
  • 89
  • 153
1

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

Alex Díaz
  • 2,303
  • 15
  • 24
0

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

echo $?

Not a C question though

pmg
  • 106,608
  • 13
  • 126
  • 198