问题
I try so send some files toward multiple servers using scp
in bash script.
But I encountering problem.
here is the shell script I wrote.
#!/bin/sh
IP_LIST=('127.0.0.x' '127.0.0.y' '127.0.0.z')
for ip_addr in "${IP_LIST[@]}"
do
echo "$ip_addr"
expect << 'EOS'
set timeout 10
spawn scp -p /home/foo/bar/baz.txt user@"$ip_addr":/home/destdir
expect "*password*"
send "pasword\r"
expect eos
exit 0
EOS
done
I assume each element in ip_addr
is assigned to the variable ip_addr
,
but in expect
session, element in the list doesn't assigned.
When I execute this script, such error message appear.
can't read "ip_addr": no such variable
while executing
"spawn scp -p /home/foo/bar/baz.txt user@"$ip_addr":/home/destdir"
It works when use echo
command(displays each element in IP_LIST
).
anybody know some good idea?
回答1:
For shell's << STRING
syntax, if STRING
is quoted then it'll not expand variables so your $ip_addr
is still $ip_addr
to the Expect script but it's not defined in Expect. You can pass the ip_addr
from shell to Expect with the env var. E.g.:
#!/bin/sh
IP_LIST=('127.0.0.x' '127.0.0.y' '127.0.0.z')
for ip_addr in "${IP_LIST[@]}"
do
echo "$ip_addr"
ip_addr=$ip_addr expect << 'EOS'
set timeout 10
spawn scp -p /home/foo/bar/baz.txt user@$::env(ip_addr):/home/destdir
expect "*password*"
send "pasword\r"
expect eos; # do you mean `eof'?
exit 0
EOS
done
回答2:
Hope this helps.
IP_LIST=('127.0.0.x' '127.0.0.y' '127.0.0.z')
for ip_addr in "${IP_LIST}"
do
echo "$ip_addr"
expect << 'EOS'
set timeout 10
spawn scp -p /home/foo/bar/baz.txt user@"$ip_addr":/home/destdir
expect "*password*"
send "pasword\r"
expect eos
exit 0
EOS
done
来源:https://stackoverflow.com/questions/40376587/how-to-use-shell-variable-in-expect-session