给出非常简单的脚本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.expect
在expect -exact "process returned with 0"
之后失败,并返回代码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
即使我更改了“应用程序”的逻辑以便能够以正/逻辑否定的流程对其进行测试,结果仍然无法解释。
我完成工作
并且不知道为什么expect
表现为这种方式。
在您的第一个脚本中,expect -exact...
命令通过timeout“成功”。默认超时为10秒,默认的超时操作为不执行任何操作。因此命令等待10秒,匹配超时,然后返回,因此我们继续执行下一个命令。
您可以明确匹配超时:
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
注意,正则表达式使用{}
样式引号,因为""
引号不允许您在其中使用[]
。