在 bash 中模拟按键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41186459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:32:46  来源:igfitidea点击:

Simulate key press in bash

bash

提问by Wojciech Szabowicz

I have a question, Im having very simple script that starts anpther binary file in loop it looka like this:

我有一个问题,我有一个非常简单的脚本,它在循环中启动 anpther 二进制文件,它看起来像这样:

for (( i=0; \$i <= 5; i++ )) ; do 
 test.sh 
done

Now problem is that after each execution test.sh asks me if I want to to override log something Like "Do you want to override log? [Y/n]"

现在的问题是,在每次执行之后 test.sh 都会问我是否要覆盖日志,例如“你想覆盖日志吗?[是/否]”

After that prompt appears scripts pauses and iteration is stopped until I manually press Y and that it continues until another prompt appears.

在出现该提示后,脚本暂停并停止迭代,直到我手动按 Y 并继续直到出现另一个提示。

To automate process can I simulate pressing "Y" button?

为了自动化过程,我可以模拟按下“Y”按钮吗?

回答by Aaron

I believe using yesmight be enough if your test.shscript doesn't use its standard input for other purposes : yeswill produce an infinite stream of lines of yby default, or any other string you pass it as a parameter. Each time the test.shchecks for user input, it should consume a line of that input and carry on with its actions.

我相信yes如果您的test.sh脚本不将其标准输入用于其他目的,使用可能就足够了:默认情况下yes会产生无限的行流y,或者您将其作为参数传递的任何其他字符串。每次test.sh检查用户输入时,它都应该使用该输入的一行并继续其操作。

Using yes Y, you could provide your test.shscript with more Ythan it will ever need :

使用yes Y,你可以为你的test.sh脚本提供Y比它需要的更多的东西:

yes Y | test.sh

To use it with your loop, you might as well pipe it to the loop's stdin rather than to the test.shinvocation :

要将它与您的循环一起使用,您最好将其通过管道传输到循环的 stdin 而不是test.sh调用:

yes Y | for (( i=0; i <= 5; i++ )) ; do 
 test.sh 
done

回答by Aserre

Something like the following code snippet should work :

像下面的代码片段应该工作:

for (( i=0; i <= 5; i++ ))
#heredoc. the '-' is needed to take tabulations into acount (for readability sake)
#we begin our expect bloc
do /bin/usr/expect <<-EOD
    #process we monitor
    spawn test.sh
    #when the monitored process displays the string "[Y/n]" ...
    expect "[Y/n]"
    #... we send it the string "y" followed by the enter key ("\r") 
    send "y\r"
#we exit our expect block
EOD
done