bash 期望中的while循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5736643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:26:49  来源:igfitidea点击:

while loops within expect

bashwhile-loopexpect

提问by Pkp

I am using expect within bash. I want my script to telnet into a box, expect a prompt, send a command. If there is a different prompt now, it has to proceed or else it has to send that command again. My script goes like this:

我在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}  
}  
}  
"  

Output:

输出:

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

Kindly help me.
I tried to change it to while [ $temp == 1] {

请帮助我。
我试着把它改成 while [ $temp == 1] {

I am still facing the error below:

我仍然面临以下错误:

Output:

输出:

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

回答by glenn Hymanman

This is how I'd implement this:

这就是我要实现的方式:

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
  • use single quotes around the expect script to protect expect variables
  • pass the shell variables as arguments to the script.
  • use "exp_continue" to loop instead of an explicit while loop (you had the wrong terminating variable name anyway)
  • 在expect脚本周围使用单引号来保护expect变量
  • 将 shell 变量作为参数传递给脚本。
  • 使用“exp_continue”来循环而不是显式的 while 循环(无论如何你的终止变量名是错误的)

回答by Bryan Oakley

The syntax for while is "while test body". There must be a spce between each of those parts which is why you get the error "no such command while)"

while 的语法是“while test body”。每个部分之间必须有一个 spce,这就是为什么您会收到错误“同时没有这样的命令)”

Also, because of tcl quoting rules, 99.99% of the time the test needs to be in curly braces. So, the syntax is:

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

while {$temp == 1} {

For more information see http://tcl.tk/man/tcl8.5/TclCmd/while.htm

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

(you probably have other problems related to your choice of shell quotes; this answer addresses your specific question about the while statement)

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