【问题标题】:Simulate key press in bash在bash中模拟按键
【发布时间】:2016-12-16 14:24:55
【问题描述】:

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

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

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

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

要自动化流程,我可以模拟按下“Y”按钮吗?

【问题讨论】:

  • expect 完全满足您的需求。
  • 也许yes 就足够了。 yes Y 将产生无限的Y 流,您可以将其通过管道输入test.sh 的标准输入。
  • 想发布答案,@Aaron?
  • 当然,为什么不呢!

标签: bash


【解决方案1】:

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

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

yes Y | test.sh

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

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

【讨论】:

    【解决方案2】:

    类似下面的代码 sn-p 应该可以工作:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-08
      • 2021-03-07
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 2012-01-30
      • 1970-01-01
      相关资源
      最近更新 更多