首页 > 解决方案 > 如何根据脚本输出的内容定义期望发送的内容?

问题描述

我有一些脚本,在执行时会返回如下内容:

1 - some option
2 - nice option
3 - bad option
4 - other option

What number do you choose?

它正在等待反馈。我希望解析此文本并始终以分配给nice option. 脚本可能会改变,所以有时可能nice option是选项号 2,有时可能是选项号 4。我该怎么做?

现在我正在做这样的事情:

expect -c 'spawn script.sh
  set timeout 3600
  expect "What number do you choose?"
  send "2\r"
  expect eof'

但是如果脚本会改变并且nice option不会低于 2,那么我就有问题了。

标签: automationexpect

解决方案


我相信我找到了解决方案,仅使用expect

expect -c 'spawn script.sh 
  expect -re {(\d)\ - nice option}
  send "$expect_out(1,string)\r"
  expect eof

expect -re将使用正则表达式匹配(\d表示“任何数字”)。因为\d是在捕获组中,或者换句话说,在括号中它被保存在正则表达式捕获组编号 1(正则表达式教程链接)中。期望您可以在此正则表达式之外引用多达9 个正则表达式捕获组,并将它们保存在$expect_out(1,string)等(Google 图书链接)中。因此,如果我们使用而不是,我们将只发送在正则表达式中匹配的数字部分,而不是返回的整个字符串。$expect_out(2,string)$expect_out(9,string)$expect_out(1,string)$expect_out(0,string)$expect_out(0,string)


推荐阅读