在bash中模拟按键

时间:2016-12-16 14:24:55

标签: bash

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

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

现在问题是每次执行后test.sh都会问我是否要覆盖日志,比如&#34;你想覆盖日志吗? [Y / N]&#34;

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

为了自动化过程,我可以模拟按下&#34; Y&#34;按钮?

2 个答案:

答案 0 :(得分:3)

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

使用yes Y,您可以为test.sh脚本提供比以前更多Y的脚本:

yes Y | test.sh

要将它与循环一起使用,您也可以将它传递给循环的stdin而不是test.sh调用:

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

答案 1 :(得分:2)

以下代码段应该有效:

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
相关问题