I want to run my program in C with bash script, also, I want my bash script to pass some values to my program in C. This is my C code (very simple, it reads as input math operations, for example: 2 + 3, saves it to file, and thats all):
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int howMany = 0, i = 0;
float num1, num2;
char sign;
FILE *fp;
if((fp=fopen("operations.txt", "w"))==NULL)
{
exit(-1);
}
printf("How many math operations would you like to pass?\n> ");
scanf("%d", &howMany);
for(i=0; i<howMany; i++)
{
printf("Pass %d operations like this: {num1 sign num2}:\n> ", i+1);
scanf("%f %c %f", &num1, &sign, &num2);
fprintf(fp, "%f ", num1);
fprintf(fp, "%c ", sign);
fprintf(fp, "%f", num2);
if(i < howMany-1)
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
Then, I have my bash script, I would like it to run my program in C and give it 9 math operations: 1+2, 3+4, … 9+10. I did it like this:
#!/bin/bash
n=9
echo "$n" | ./app
for (( i=1; $i < 10; i++ )) ; do
let "c=$i+1"
echo $i "+" $c | ./app
done
but theres a problem it doesnt work as I want it to. Please, help – only with this bash script, my C program works just great.
The problem is that you’re executing your
./appseveral times, each time feeding it a small part of the whole.You can group the commands and then pipe it all to one instance of your app like this: