how to send text to a process in a shell script?
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 pro开发者_运维知识库gram - send text to a process - receive output from that programMany thanks.
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
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.
I assume you want a script written in bash.
- To open a file you just need to type a name of it.
- To send a text to a program you either pass it through
|
or with<
(take input from file) - 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
精彩评论