在 Expect 中使用 While 循环时没有这样的变量

No Such Variable When Using While Loop in Expect

我试图在 expect 的 while 循环中访问一个变量,但我一直收到一个错误,指出该变量不存在。有问题的代码:

#!/usr/bin/expect
spawn ./simulator.sh
set timeout 1

...<extra code>...

# Return the time in seconds from epoch
proc getTime {year month day hour minute} {
    set rfc_form ${year}-${month}-${day}T${hour}:${minute}
    set time [clock scan $rfc_form]
    return $time
}

# Get a handle to the file to store the log output
set fileId [open $filename "a"]
# Get one line at a time
expect -re {.*the number of lines from the debug log file to appear on one page.*}
send "1\r"
# Get the initial time stamp and store the first line
expect -re {^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})\..*$} {
    puts -nonewline $fileId $expect_out(0,string)
    set initTime $expect_out(1,string) $expect_out(2,string) $expect_out(3,string) $expect_out(4,string) $expect_out(5,string)
}
send "1\r"
# Iterate over the logs until we get at least 5 minutes worth of log data
while { true } {
    expect -re {^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})\..*$} {
        puts -nonewline $fileId $expect_out(0,string)
        set currentTime $expect_out(1,string) $expect_out(2,string) $expect_out(3,string) $expect_out(4,string) $expect_out(5,string)
    }
    # 300 = 5 minutes * 60 seconds
    if { $initTime - $currentTime > 300 } break
    expect -re {.*enter.*}
    send "n\r"
}

...<extra code>...

我得到的错误是:

$ ./test.sh
the number of lines from the debug log file to appear on one page1
201505151624.00 721660706 ns | :OCA (027):MAIN (00) | CONTROL |START LINE
enter1
201505151620.00 022625203 ns | :OCA (027):MAIN (00) | CONTROL |com.citrix.cg.task.handlers.ADDeltaSyncHandler:ThreadID:1182, Delta sync on:activedirectory2
entercan't read "initTime": no such variable
    while executing
"if { $initTime - $currentTime > 300 } break"
    ("while" body line 7)
    invoked from within
"while { true } {
        expect -re {^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})\..*$} {
                puts -nonewline $fileId $expect_out(0,string)
                set currentTime $expect_o..."
    (file "./test.sh" line 42)

我确定我正在做一些非常愚蠢的事情,但我一辈子都想不通。提前感谢您的帮助!

此预期模式不匹配:

expect -re {^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})\..*$} {
    puts -nonewline $fileId $expect_out(0,string)
    set initTime $expect_out(1,string) $expect_out(2,string) $expect_out(3,string) $expect_out(4,string) $expect_out(5,string)
}

你会知道它是否匹配,因为你会得到一个语法错误:set 命令只有一个或两个参数,而你给了它 6.

exp_internal 1 添加到 spawn 命令之前的一行,expect 将向您显示详细的调试信息,让您了解您的模式是否匹配。

要解决 set 语法错误,您可能需要

    set initTime [getTime $expect_out(1,string) $expect_out(2,string) $expect_out(3,string) $expect_out(4,string) $expect_out(5,string)]

此外,在 if 条件下,请注意 $initTime 将比 $currentTime ,因此 {$initTime - $currentTime > 300}永远不会是真的,所以你的循环将是无限的。