我的bash脚本中有一个数组
Sample.sh
my_file=("a.txt" "b.txt" "c.txt" "d.txt" "e.txt")
现在在同一文件中,我想使用Expect并进行循环以获取sftp中的某些文件。这是我的代码
/usr/bin/expect <<EOF
set timeout -1
array set param ${!my_file[@]}
spawn sftp $sftp_option $user@$host
expect "Password:"
send "$pswd\r"
expect "sftp>"
for arg in $param; do
send "mget $arg*\r"
expect "sftp>"
done
send "bye\r"
EOF
使用该代码,我无法使用上述数组进行循环。而且我有这样的错误
错误#args:应为“数组集arrayName列表”在执行时“数组集参数0 1”
在bash和Expect之间没有单独的文件的情况下,是否可以解决此问题?
为什么要在bash脚本的期望块中打扰命令行处理。
相反,您可以执行以下操作:
#!/bin/bash
my_file=("a.txt" "b.txt" "c.txt" "d.txt" "e.txt")
for file in "${my_file[@]}"; do
/usr/bin/expect <<EOF
set timeout -1
spawn sftp $sftp_option $user@$host
expect "Password:"
send "$pswd\r"
expect "sftp>"
send "mget $file*\r"
expect "sftp>"
send "bye\r"
EOT
done
用于插入数组值的正确语法是
array set param ${my_file[@]}
没有!
,但这会产生
array set param a.txt b.txt c.txt d.txt e.txt
没有报价。
但是,用于创建数组的Expect语法看起来像
array set param {one one.txt two two.txt}
具有交替的键和值(更像是关联数组,而不仅仅是值列表)。但是,您仍然不能在Expect脚本中使用shell for
循环;该脚本使用完全不同的语法(期望基于TCL,而不是Shell脚本)。
可能您正在寻找类似的东西
/usr/bin/expect <<EOF
set timeout -1
spawn sftp $sftp_option $user@$host
expect "Password:"
send "$pswd\r"
expect "sftp>"
foreach arg {${my_file[@]}} {
send "mget $arg*\r"
expect "sftp>"
}
send "bye\r"
EOF
我在Pass bash array to expect script中写下了适当的TCL循环语法