期望 tcl "file exists" 函数失败,即使 "ls" 显示文件

Expect tcl "file exists" function failing even though "ls" shows file

我用 spawn sh 生成了一个 shell 实例,并且我 运行 一些命令来生成文件。然后我使用下面的 verify_file_exists 来检查它们是否已创建。但是使用 file exists 总是失败!我编辑了以下程序以进一步说明我的问题。我显式创建 hello.txt 并检查它是否存在,但它总是失败。

proc verify_file_exists {filename} {
    send "touch hello.txt\r"
    if {[file exists hello.txt]} {
        puts "hello.txt found\r"
    } else {
        puts "Failed to find hello.txt\r" # Always fails
        exit 1
    }
}

我也尝试了其他方法:我在调用 verify_file_exists 之前放置了一个 interact ++ return 语句,这使我进入了 sh 实例。我然后 运行 touch hi.txt,然后 运行 expect 并输入一个 expect 实例。那么如果我运行file exists hi.txt得到1的正面回应!所以这不可能是权限问题,对吧?

如果我执行与上述相同的操作,但手动 touch hello.txt,程序仍然在 file exists 行失败。

为什么 file exists 不像 expected 那样工作?

注意:在 hello.txt 周围加上引号并不能解决问题。

send之后,您需要等待下一个shell提示出现,这意味着最后一个命令已经完成。这就是 send 通常后跟 expect 的原因。为了快速测试,您还可以在 send.

之后添加 sleep 1

另一种可能是 Expect 进程的当前目录与 spawned shell 进程的当前目录不同。

两者的一个简单示例:

[STEP 101] $ cat example.exp
proc expect_prompt {} {
    expect -re {bash-[.0-9]+[#$] $}
}

spawn bash --norc
expect_prompt

send "rm -f foo bar && touch foo\r"
expect_prompt
if { [file exists foo] } {
    send "# found foo!\r"
    expect_prompt
}

send "mkdir -p tmp && cd tmp && rm -f bar && touch bar\r"
expect_prompt
if { ! [file exists bar] } {
    send "# where's bar?\r"
    expect_prompt
}

send "exit\r"
expect eof
[STEP 102] $ expect example.exp
spawn bash --norc
bash-4.4$ rm -f foo && touch foo
bash-4.4$ # found foo!
bash-4.4$ mkdir -p tmp && cd tmp && rm -f bar && touch bar
bash-4.4$ # where's bar?
bash-4.4$ exit
exit
[STEP 103] $