views:

34

answers:

3

So I have a Linux program that runs in a while(true) loop, which waits for user input, process it and print result to stdout.

I want to write a shell script that open this program, feed it lines from a txt file, one line at a time and save the program output for each line to a file.

So I want to know if there is any command for:
- open a program
- send text to a process
- receive output from that program

Many thanks.

A: 

It sounds like you want something like this:

cat file | while read line; do
    answer=$(echo "$line" | prog)
done

This will run a new instance of prog for each line. The line will be the standard input of prog and the output will be put in the variable answer for your script to further process.

Some people object to the "cat file |" as this creates a process where you don't really need one. You can also use file redirection by putting it after the done:

while read line; do
    answer=$(echo "$line" | prog)
done < file
R Samuel Klatchko
Would the downvoter care to explain what he or she finds incorrect?
R Samuel Klatchko
+1  A: 

Have you looked at pipes and redirections ? You can use pipes to feed input from one program into another. You can use redirection to send contents of files to programs, and/or write output to files.

Brian Agnew
+1  A: 

I assume you want a script written in bash.

  1. To open a file you just need to type a name of it.
  2. To send a text to a program you either pass it through | or with < (take input from file)
  3. To receive output you use > to redirect output to some file or >> to redirect as well but append the results instead of truncating the file

To achieve what you want in bash, you could write:

#/bin/bash

cat input_file | xargs -l1 -i{} your_program {} >> output_file

This calls your_program for each line from input_file and appends results to output_file

pajton