在expect中使用while循环

5

我正在使用bash中的expect。我想让我的脚本telnet到一个框中,等待提示,发送命令。如果现在有不同的提示,它必须继续执行,否则它必须再次发送该命令。 我的脚本如下:

\#!bin/bash  
//I am filling up IP and PORT1 here  
expect -c "    
set timeout -1  
spawn telnet $IP $PORT1  
sleep 1  
send \"\r\"  
send \"\r\"  
set temp 1  
while( $temp == 1){    
expect {  
Prompt1 { send \"command\" }  
Prompt2 {send \"Yes\"; set done 0}  
}  
}  
"  

输出:

invalid command name "while("  
    while executing  
"while( == 1){" 

请帮我。

我试图将其更改为while [ $temp == 1] {

然而,我仍然遇到以下错误:

输出:

invalid command name "=="  
    while executing  
"== 1"  
    invoked from within  
"while [  == 1] {  
expect {

1
你可能想先编写一个纯 expect 脚本来调试此问题,这样就不必担心 shell 引用规则会以微妙的方式更改你的 expect 脚本。 - Bryan Oakley
因为你的脚本是双引号,所以 shell(而不是 expect)正在用空值替换 $temp,导致出现奇怪的错误。 - glenn jackman
2个回答

14

这是我会实现它的方式:

expect -c '
  set timeout -1  
  spawn telnet [lindex $argv 0] [lindex $argv 1]  
  send "\r"  
  send "\r"  
  expect {  
    Prompt1 {
      send "command"
      exp_continue
    }  
    Prompt2 {
      send "Yes\r"
    }  
  }  
}  
'  $IP $PORT1
  • 用单引号来保护expect变量
  • 将shell变量作为参数传递给脚本。
  • 使用"exp_continue"来循环,而不是显式的while循环(你的终止变量名也不正确)

成功了!!非常感谢!!但是我有一个问题,当我们使用exp_continue时,如果没有看到prompt2,它会再次发送“command”吗?我的意思是在循环中。还是只发送一次命令并等待prompt2? - Pkp
当它看到Prompt1时,它会发送命令,然后返回expect块的顶部,并等待Prompt1或Prompt2。当它看到Prompt2时,它发送Yes并退出该块。 - glenn jackman

4

while循环的语法是“while 测试条件 循环体”。每个部分之间必须有一个空格,这就是为什么会出现错误“no such command while)”。

此外,由于tcl的引号规则,99.99%的情况下,测试条件需要用花括号括起来。因此,正确的语法是:

while {$temp == 1} {

更多信息请参见http://tcl.tk/man/tcl8.5/TclCmd/while.htm。您可能还有其他与shell引号选择相关的问题;本答案仅回答关于while语句的具体问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接