【问题标题】:for loop expect results differents between interactive and script [duplicate]for循环期望交互和脚本之间的结果不同[重复]
【发布时间】:2021-04-22 14:39:58
【问题描述】:

在这个链接上,我已经阅读了 for loop management for except https://tcl.tk/man/tcl8.6/TclCmd/for.htm

如果你调用 expect 并将代码粘贴进去,你会得到正确的行为:

@gigi:~$ expect
expect1.1> for {set x 0} {$x<10} {incr x} {
    puts "x is $x"
}+> +> 
x is 0
x is 1
x is 2
x is 3
x is 4
x is 5
x is 6
x is 7
x is 8
x is 9
expect1.2> 

如果你从 bash 脚本传递它,它会出错:

^@gigi:~expect -d << EOD
> for {set x 0} {$x<10} {incr x} {
>     puts "x is $x"
> }
> EOD
expect version 5.45.4
argv[0] = expect  argv[1] = -d  
set argc 0
set argv0 "expect"
set argv ""
executing commands from command file
missing operand at _@_
in expression "_@_<10"
    (parsing expression "<10")
    invoked from within
"for {set x 0} {<10} {incr x} {
    puts "x is "

为什么这个例子的工作方式不同?

【问题讨论】:

  • $x 在此处文档中展开。
  • 在 shell 中嵌入 Expect 很棘手。看看我的sexpect (Expect for Shells),您可以用它来编写仅使用shell 代码的Expect 脚本。

标签: bash tcl expect


【解决方案1】:

您遇到的问题是bash 在将脚本传递给expect 之前已扩展了您将脚本放入的here-doc 中的变量。来自bash 联机帮助页:

here-documents的格式为:

[n][-]单词
here-document
分隔符

无参数和变量扩展、命令替换、算术 word 上执行扩展或路径名扩展。如果任何部分 word 被引用,delimiter 是在 word 上去掉引号的结果, 并且 here-document 中的行没有展开。如果 word 是 未引用,此处文档的所有行都受参数 扩展,命令替换和算术扩展,字符 序列 \ 被忽略,并且必须使用 \ 来引用 字符 \$`

这意味着一种解决方法是使用expect -d &lt;&lt; 'EOD' 而不是expect -d &lt;&lt; EOD

expect -d << 'EOD'
    for {set x 0} {$x<10} {incr x} {
        puts "x is $x"
    }
EOD

另一个(劣质!)是反斜杠引用$ 字符;它的劣势是因为真正的期望脚本通常包含自己的反斜杠,并且事情会变得非常丑陋和复杂。但是,最好这样做:

把expect脚本放在它自己的文件中,myfile.exp,然后这样称呼它:expect -d -f myfile.exp。试图将 Tcl 代码放在这样的 Bash 脚本中是自找麻烦。

请注意,这确实意味着从 bash 传递变量有点尴尬。但是你会从编码的理智性大大提高中获益。

【讨论】:

    猜你喜欢
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    相关资源
    最近更新 更多