1

I have a C program that I compile to make an executable file. I want to make a script that starts the C program, runs several commands that the script contains and eventually exits the script. The C program requires its inputs (commands) as user specified arguments.

I tried scripting something like this:

#/bin/bash
./program
command 1
command 2
..
quit # A quit command within the program

But the program does not seem to understand that after I start the execution that the following commands should be arguments to the C program.

I tried to check the commands of my program, but maybe a separate C program that checks this would be better. How would you suggest that it be debugged?

1
  • Once your program starts the other lines do not occur until it finishes (and then they are run as shell commands). If your program reads from standard input then you can just pipe the commands to it. Commented Oct 9, 2015 at 18:00

3 Answers 3

3

You need to tell the shell script that the commands are input to the program:

#!/bin/bash

./program << END
command 1
command 2
..
quit    
END

The << operator tells the shell that the following lines are fed to stdin of the given program until it finds a line that says only END.

Sign up to request clarification or add additional context in comments.

3 Comments

Notice that with this approach, it's impossible to feed other input to the stdin of program.
Thanks it was something like this I looked for. I managed to run the commands from another file with "./program < otherFile", but I liked this more.
For completeness' sake: this technique is called a "here document" or "heredoc".
1

For a simple case, you can just feed a string of inputs to your program, e.g.

echo -e "command 1\ncommand 2\n" | ./program

If you need to interact with your program (e.g. wait for some output and maybe react on it), you might want to evaluate the expect tool.

Comments

0

First program:

#include <stdio.h>

int main(int argc, char *argv[])
{
        while ( *++argv  )
                printf("%s\n", *argv);
        return 0;
}

Second program:

#!/bin/bash

./program1 argument1 argument2 argument3

A common scripting idiom is to use \ backslash characters to continue a command's argument parameters to the next line. As follows:

#!/bin/bash

./stack1 \
argument1 \
argument2 \
argument3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.