我在bash脚本中使用expect脚本。当我在期望脚本中使用foreach时,它会抛出
错误#args:应该是“foreach varList list?varList list ...?command”
代码:
#!/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"
由于
答案 0 :(得分:2)
heredoc(<<ENDTOK
)在$variables
上受到shell扩展。这意味着对于您希望解释的每个$variable
,您需要转义$
。
逃避某事的方法是在其前面添加一个斜杠($
- &gt; \$
)。
看来用户名和密码应该来自shell,其余来自期望,所以这是应该如何:
#!/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"
请注意\
和$SERVERS
前面的${SERVER}
。
答案 1 :(得分:1)
您需要使用反斜杠转义美元符号,因为$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
答案 2 :(得分:0)
如果引用here-document分隔符,嵌入式脚本也会被有效引用:
/bin/expect -<<'EOD'
... expect script as posted ...
EOD