Capturing the output and input of an interactive program using bash

I am working on automating the interactive command line of a Java program in bash to verify that the program produces the correct output for input (basically testing a module with a low level of service in bash).

For example, if I have a Java program that asks the user to enter the full name and then displays only their name, it should look something like this:

Enter your name: John Doe
John

Where user "John Doe" was entered by the user.

A simple bash command to run might look like this:

OUTPUT=`echo "John Doe" | java NameReader`

or

OUTPUT=`java NameReader <<< "John Doe"`

The problem with both of them is that $ OUTPUT now contains the following:

Enter your name: John

Since the text that was sent to stdin (and its accompanying new line) is not reproduced at the output of the program as we see it in the console.

$OUTPUT :

Enter your name: John Doe
John

:

Enter your name: 
John

( , , )

bash ( java-), , stdin, stdout "", java, ?

( : , spawn/expect , , , , )

+4
3

script

script -q -c "java NameReader" log.txt

java NameReader log.txt.

+2

Java- :

import java.util.Scanner;
class A {
        public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                System.out.println(sc.next());
        }
}

bash script,

Enter your name: John
John Doe

Enter your name: John Doe
John

bash script:

#!/bin/bash
arg1Outpt=`eval "$1"`
javaOut=`echo "$arg1Outpt" | eval "$2"`
#prints Enter your name: John\nJohn Doe      
echo "${javaOut}"$'\n'"${arg1Outpt}" |
                        sed 'N; s/\(Enter your name: \)\(.*\)\(\n\)\(.*\)/\1\4\3\2/'
                        #and this is a multiline sed(man sed) that transforms your 
                        #input into what you want :)

:

bash pipeCheat.bash 'echo "john doe"' 'java A'

pipeCheat.bash - , script .

, .

+1

. , -, - :

{ sleep 3; echo "John Doe" | tee -a out.txt; } | java  NameReader >> out.txt
OUTPUT=`cat out.txt`
rm out.txt

, script :

  • 3 , "John Doe" , out.txt
  • java-.

tee, ( java ), . -a , .

java out.txt( → ).

OUTPUT .

, ...

  • , java 3 . , . ( ) , 3 , , , .
  • 3 , . java 1 , 2 , . , .
  • , . , "sleep/echo/tee" , , .

... So this is the best that I have now. Of course, the best solutions are still being offered.

0
source

All Articles