【问题标题】:while loops within expect预期内的while循环
【发布时间】:2011-08-09 20:21:27
【问题描述】:

我在 bash 中使用期望。我希望我的脚本 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 {

【问题讨论】:

  • 您可能希望在调试此问题时首先编写一个纯期望脚本,这样您就没有可能以微妙方式改变您的期望脚本的 shell 引用规则。
  • 看起来很奇怪的错误是怎么回事:因为你的脚本是双引号的,所以 shell(不期望)用空值替换 $temp

标签: bash while-loop expect


【解决方案1】:

这就是我的实现方式:

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
  • 在期望脚本周围使用单引号来保护期望变量
  • 将 shell 变量作为参数传递给脚本。
  • 使用“exp_continue”来循环而不是显式的while循环(无论如何你的终止变量名是错误的)

【讨论】:

  • 成功了!!非常感谢!!但是有一个查询,当我们输入 exp_continue 时,如果它没有看到 prompt2,它会再次发送“命令”吗?我的意思是在一个循环中。还是发送一次命令,一直等待prompt2?
  • 当它看到 Prompt1 时,它会发送命令,然后回到期望块的顶部并等待 Prompt1 或 Prompt2。当它看到 Prompt2 时,它会发送 Yes 并且只是掉出块。
【解决方案2】:

while 的语法是“while 测试体”。每个部分之间必须有一个 spce,这就是为什么您会收到错误“no such command while)”

另外,由于 tcl 引用规则,99.99% 的时间测试需要在花括号中。所以,语法是:

while {$temp == 1} {

欲了解更多信息,请参阅http://tcl.tk/man/tcl8.5/TclCmd/while.htm

(您可能还有其他与您选择 shell 引号相关的问题;这个答案解决了您关于 while 语句的具体问题)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 2016-03-14
    • 2011-06-19
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多