如果输出不匹配,如何使 expect 的 expect 命令失败?

How to make expect's expect command fail if the output isn't matched?

给定非常简单的脚本script.expect

#!/usr/bin/expect

spawn bash
expect "#"
send "/bin/false; echo \"process returned with $?\"\r"
expect -exact "process returned with 0"
send -- "exit\r"
expect eof

我似乎不知道脚本如何不失败,因为 /bin/false 会导致 echo 命令打印 process returned with 1,因此 process returned with 0 永远不会在 expect 命令上匹配。我希望 expect script.expectexpect -exact "process returned with 0".

之后以 return 代码 1 失败
#!/usr/bin/expect

spawn bash
expect "#"
send "/bin/true; echo \"process returned with $?\"\r"
expect -exact "process returned with 0" {
  send -- "exit\r"
  expect eof
  exit 0
}
exit 1

即使我更改 "application" 的逻辑以便能够使用 positive/logically 否定流对其进行测试,结果仍然无法解释。

我完成了

不知道为什么 expect 会这样。

在您的第一个脚本中,expect -exact... 命令是 "succeeding",带有 超时 。默认超时为 10 秒,超时时的默认操作是什么都不做。所以命令等待 10 秒,匹配超时,returns,所以我们继续下一个命令。

您可以显式匹配超时:

expect {
    -exact "process returned with 0" {}
    timeout { puts "timeout!"; exit 1 }
}

为避免等待超时,您可以使用正则表达式来匹配 $? 是 0 还是 1(或其他数字)。如果将正则表达式的一部分放在捕获组 () 中,则可以在内置变量 $expect_out(1,string):

中找到它
expect -re {process returned with ([0-9]+)}
set returncode $expect_out(1,string)
puts "we got $returncode"
exit $returncode

请注意,正则表达式使用 {} 样式引号,因为 "" 引号不允许您在其中使用 []