简体   繁体   中英

How to run a c program in bash script and give it some values?

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 ./app several 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:

#!/bin/bash
{ 
n=9
echo "$n" 

for (( i=1; $i < 10; i++ )) ; do
       let "c=$i+1" 
       echo $i "+" $c
done
} | ./app

It's because you're running independent instances of ./app , giving each less than the full amount of data it expects. You can get round it with something like:

(
    n=9
    echo "$n"

    for (( i=1; $i < 10; i++ )) ; do
        let "c=$i+1" 
        echo $i "+" $c
     done
) | ./app

This runs the entire set of commands within () as a single sub-shell and pipes the output of the lot into a single instance of your application.


An even better approach may be to use random data, such as with:

#!/bin/bash

(
    (( count = $RANDOM % 100  + 1 ))
    echo ${count}

    while [[ ${count} -gt 0 ]] ; do
        (( val1 = $RANDOM % 100 ))
        (( op   = $RANDOM % 2 + 1 ))
        (( val2 = $RANDOM % 100 ))
        op=$(echo '+-' | cut -c${op}-${op})
        echo ${val1} ${op} ${val2}
        (( count = count - 1 ))
    done
) | ./app

This will give you things like:

9
9 - 91
56 - 4
85 + 25
23 + 15
6 + 86
10 - 26
99 - 26
19 + 31
33 - 60

which may provide better coverage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM