This question has been asked for many languages but I have yet to find the bash-flavored duplicate.
Suppose I have a program that alternates between writing stdout and reading stdin.
#include <stdio.h>
/*
* Control_D to exit.
*/
int main(int argc, char** argv){
char init = 'C';
if (argc > 1) {
init = *argv[1];
}
putchar(init);
putchar('\n');
while (1) {
int c = getchar();
if (c == -1) {
return 0;
}
putchar(c);
putchar('\n');
}
}
I would like to write a bash script that reads what the program wrote and then decides what to write standard input, and does this repeatedly. That is, something like this:
myProgram &
for i in $(seq 1 10);
do
output=$(# magic command to read myProgram stdout)
if [[ $output = "C" ]]; then
# Magic command to write 'C' to myProgram input
fi
if [[ $output = "D" ]]; then
# Magic command to write 'E' to myProgram input
done
I initially tried to do this with named pipes but this did not work because pipes require both ends to be open before starting and using various exec tricks did not manage to workaround these limitations. I am not ruling them out as a solution, merely pointing out that I was not sufficiently clever to get them to work.
Do these magic commands exist in bash, or do I have to switch to another language?
Let's assume for the sake of this question that I have no control over myProgram and cannot dictate how it communicates; it only understands stdin and stdout because it was intended to be used interactively by a user.