Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash while循环在expect中_Bash_While Loop_Expect - Fatal编程技术网

Bash while循环在expect中

Bash while循环在expect中,bash,while-loop,expect,Bash,While Loop,Expect,我在bash中使用expect。我想让我的脚本远程登录到一个框中,期待一个提示,发送一个命令。如果现在有不同的提示,则必须继续,否则必须再次发送该命令。 我的剧本是这样的: \#!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 w

我在bash中使用expect。我想让我的脚本远程登录到一个框中,期待一个提示,发送一个命令。如果现在有不同的提示,则必须继续,否则必须再次发送该命令。 我的剧本是这样的:

\#!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){" 
invalid command name "=="  
    while executing  
"== 1"  
    invoked from within  
"while [  == 1] {  
expect {
请帮帮我。
当[$temp==1]{

我仍然面临以下错误:

输出:

invalid command name "while("  
    while executing  
"while( == 1){" 
invalid command name "=="  
    while executing  
"== 1"  
    invoked from within  
"while [  == 1] {  
expect {
while的语法是“while test body”。这些部分之间必须有一个spce,这就是为什么会出现错误“while没有这样的命令”

此外,由于tcl引用规则,99.99%的测试时间需要使用大括号。因此,语法为:

while {$temp == 1} {
有关更多信息,请参阅


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

我将如何实现此功能:

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

在调试此问题时,您可能希望首先编写一个纯expect脚本,这样您就不会有shell引用规则以微妙的方式潜在地更改您的expect脚本。奇怪的错误发生了什么:因为您的脚本是双引号的,所以shell(非expect)正在用空值替换
$temp
。它成功了!!非常感谢!!但是有一个查询,当我们将exp\u continue放入时,它是否发送“command”同样,如果它没有看到prompt2??我的意思是在循环中。或者发送一次命令并一直等待prompt2?当它看到Prompt1时,它将发送命令,然后返回到expect块的顶部并等待Prompt1或prompt2。当它看到prompt2时,它发送Yes并从块中掉出来。