简体   繁体   中英

Giving inputs to a Java program through a bash script

I have a simple java program (think of it as Apple's Siri) that, when started from a terminal, waits for a user to type in a question and then it prints out a reply. I would like to make a bash script that starts the java program and then gives it a couple of questions (just as if a human was typing them in). This is what I tried:

#!/bin/bash
# change to project directory
cd C:/JavaProjects/VirtualButler

#compile the program
javac Alfred.java

#start the program
java Alfred

#Give it questions
echo Hey what time is it?\r
echo When is my next meeting?\r

#keep the terminal open so I can see the answer
PAUSE

However, when I run the bash script, the processing gets stuck at Java Alfred line (which is running on the open cmd, waiting for the user to type in questions and use the program. Only when I terminate the Java program, the processing moves on and gets to the questions that I want to automatically pass to the Java program. Is there a way to automatically pass these questions to the java program while it is running in the cmd?

Assuming bash 4.0 and up, you can use the coproc command.

# Starts Alfred in a background process with pipes in and out of it
coproc java Alfred
# Alfred's stdin is now referred to with ${COPROC[1]}
echo Hey what time is it?\r >&${COPROC[1]}
echo When is my next meeting?\r >&${COPROC[1]}
# Alfred's stdout is found with ${COPROC[0]}
cat <&${COPROC[0]}

Note that, from here, cat will hang as there is no EOL on the file descriptor. If Alfred quits running, then cat will stop. I'll leave it to you to figure out how to tell when Alfred is done and what to do then.

这将重定向输入:

java Alfred < <(printf "Hey what time is it?\r When is my next meeting?\r")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM