如何根据脚本输出的内容来定义期望将发送什么?

How to define what expect will send, based on what is the content of script output?

我有一些脚本,在执行时 returns 是这样的:

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

What number do you choose?

正在等待反馈。我希望 expect 解析此文本并始终使用分配给 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下,那我就有问题了。

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

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

expect -re 将使用正则表达式进行匹配(\d 表示 "any digit")。因为 \d 在捕获组中,或者换句话说,在括号中它被保存在正则表达式捕获组编号 1 (regexp tutorial link). In expect you can reference up to 9 regex capturing groups, outside of this regex, and they are saved in $expect_out(1,string), $expect_out(2,string) etc up to $expect_out(9,string) (Google Books link) 中。因此,如果我们使用 $expect_out(1,string) 而不是 $expect_out(0,string),我们将仅发送在正则表达式中匹配的数字部分,而不是 $expect_out(0,string) return.[=22= 的整个字符串]