tags:

views:

295

answers:

3

I am going to be running a C program from inside a bash script.

The c program expects inputs from the user. total number of inputs are 7. which are on 7 different lines. for example

Please enter input1: 
1
Please enter input2: 
2
Please enter input3:
3

so on.. I did some reading up and found out that bash here strings are used for this purpose. So I ran the program, from inside a bash script with the following command

./runnable <<< 1

this solves the purpose when the input is required only once...what is the solution when multiple inputs will be required?

+1  A: 

expect.

chaos
+2  A: 

Generally the answer might be probably "it depends", but if the program is something like this:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  char s1[100], s2[100];
  printf("Enter string1:");
  fflush(stdout);
  fgets(s1, sizeof(s1), stdin);
  printf("Enter string2:");
  fflush(stdout);
  fgets(s2, sizeof(s2), stdin);
  printf("string1: '%s', string2: '%s'\n", s1, s2);
  exit(1);
}

Then you can feed it input using the "document here" syntax:

$ ./a.out <<_END_ 
> string1
> string2
> _END_
Enter string1:Enter string2:string1: 'string1
', string2: 'string2
'

This syntax is something that has become more than just shell - it's also a handy construct in Perl and Ruby.

Andrew Y
A: 

A lot of it depends on exactly how your program is parsing it's input. Many C programs can and will parse space-delimited integers without difficulty, so something like:

#!/bin/bash
./runnable <<< "1 2 3"

would be the easiest solution. If the program does require a carriage return after each number, then:

#!/bin/bash
./runnable <<< "1
2
3"

could do the trick. Please note the quotes around the input strings of both example -- they make the difference between "working" and "not working", although for the life of me I can't recall exactly why it's necessary for the first one.

goldPseudo