[英]How to detect on waiting for user input from bash script?
My bash script looks like: 我的bash脚本如下所示:
read -p "Do you wish to continue?" yn
# further actions ...
And I just want to interact with this script using nodejs / child_process. 我只想使用nodejs / child_process与该脚本进行交互。 How can I detect that it's waiting for the user input?
如何检测到它正在等待用户输入?
var spawn = require('child_process').spawn;
var proc = spawn('./script.sh');
proc.stdout.on("data", function(data) {
console.log("Data from bash");
}
proc.stdin.on("data", function(data) {
console.log("Data from bash"); // doesn't work :/
}
Thank you! 谢谢!
Have you try to use "expect" http://en.wikipedia.org/wiki/Expect ? 您是否尝试过使用“期望” http://en.wikipedia.org/wiki/期望? It's a tool that "expect" some text (it use regular expression) and the bash script can automatically answers.
这是一个“期望”某些文本的工具(它使用正则表达式),bash脚本可以自动应答。
From the bash man page : 在bash手册页中 :
read -p prompt
Display prompt on standard error , without a trailing newline, before attempting to read any input.
在尝试读取任何输入之前,显示标准错误提示,不带换行符。 The prompt is displayed only if input is coming from a terminal .
仅当输入来自终端时才显示提示。
And I don't think there a any way in node.js to detect that the script is waiting for input. 而且我认为node.js中没有任何方法可以检测到脚本正在等待输入。 The problems is actually that bash detects a non-terminal and disables the output to standard error.
问题实际上是bash检测到非终结符并将输出禁用为标准错误。 And even then you would have to read from stderr and not stdin to detect any waiting states .
即使这样,您也必须从stderr读取而不是stdin来检测任何等待状态 。
In the end, as Antoine pointed out, you might have to use tools like empty or Expect to wrap your shell-scripts and trick Bash to think it is in a terminal. 最后,正如Antoine指出的那样,您可能必须使用empty或Expect之类的工具来包装您的shell脚本,并欺骗Bash认为它在终端中。
Btw.: proc.stdin.write("yes\\n")
works fine. 顺便说一句:
proc.stdin.write("yes\\n")
工作正常。 Thus you could work with the script, but won't get any prompts on proc.stderr
and will not know when the script actually reads the input. 因此,您可以使用脚本,但不会在
proc.stderr
上收到任何提示,并且不会知道脚本何时实际读取输入。 You can also immediately proc.stdin.write
the input even if the script is not yet at the read -p
statement. 即使脚本尚未位于
read -p
语句中,您也可以立即proc.stdin.write
输入。 The input is buffered until the scripts eats it up. 输入被缓冲,直到脚本将其耗尽为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.