期望里面 bash + 错误 # args: 应该是“foreach varList list ?varList list ...? command”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8318504/
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-18 01:07:10  来源:igfitidea点击:

expect inside bash + wrong # args: should be "foreach varList list ?varList list ...? command"

bashexpect

提问by Tivakar

I am using expect script inside bash script. When I use foreach inside expect script, it throws

我在bash脚本中使用expect脚本。当我在期望脚本中使用 foreach 时,它会抛出

wrong # args: should be "foreach varList list ?varList list ...? command"

错误 # args: 应该是“foreach varList list ?varList list ...? command”

The code:

编码:

#!/bin/bash

read -p "Enter username: " username
read -s -p "Enter password: " password

#Expect script
/bin/expect -<<EOD 

set SERVERS {100 101 102}

foreach SERVER $SERVERS {
set timeout -1
spawn scp ${username}@plsa${SERVER}.corp.com:/log.2011-11-24 ${SERVER} 
expect "*password:"; send "$password\r"
expect eof }
EOD

echo "completed"

Thanks

谢谢

回答by Kevin

The heredoc (<<ENDTOK) is subject to shell expansion on the $variables. That means for each of the $variables you want expect to interpret, you'll need to escape the $.

Heredoc( <<ENDTOK) 在$variables. 这意味着对于$variable您希望解释的每个s,您都需要转义$.



The way to escape something is to prepend a slash to it ($-> \$).
It appears the username and password are supposed to come from the shell, the rest from within expect, so here's how that should go:

逃避某些东西的方法是在它前面加上一个斜杠($-> \$)。
看来用户名和密码应该来自shell,其余的来自expect,所以应该怎么做:

#!/bin/bash

read -p "Enter username: " username
read -s -p "Enter password: " password

#Expect script
/bin/expect -<<EOD 

set SERVERS {100 101 102}

foreach SERVER $SERVERS {
set timeout -1
spawn scp ${username}@plsa${SERVER}.corp.com:/log.2011-11-24 ${SERVER} 
expect "*password:"; send "$password\r"
expect eof }
EOD

echo "completed"

Note the \in front of $SERVERSand ${SERVER}.

请注意\前面$SERVERS${SERVER}

回答by Adam Zalcman

You need to escape dollar signs with a backslash since $nameis expended to the value of variable name:

你需要用反斜杠转义美元符号,因为它$name被消耗到变量的值name

/bin/expect -<<EOD 

set SERVERS {100 101 102}

foreach SERVER $SERVERS {
set timeout -1
spawn scp ${username}@plsa${SERVER}.corp.com:/log.2011-11-24 ${SERVER} 
expect "*password:"; send "$password\r"
expect eof }
EOD

回答by glenn Hymanman

If you quote your here-document delimiter, the embedded script is effectively quoted too:

如果引用 here-document 分隔符,则嵌入的脚本也被有效引用:

/bin/expect -<<'EOD' 
... expect script as posted ...
EOD