将包含文件列表的数组传递给期望脚本

Pass an array with a list of files to an expect script

我写了一个 bash 脚本,可以移动、复制和重命名一些文件。 在此之后,它将列表文件加载到数组中。

现在,我想将数组传递给我的 expect 脚本,它将上传文件 通过 SFTP 到目的地。

对于单个变量中的文件,我这样做:

/path/to/script/expect.sh $file

这个 expect 脚本运行良好:

#!/usr/bin/expect

set file [lindex $argv 0]

spawn sftp user@destination.com
expect "Password:"
send "password\r"
expect "sftp> "
send "put $file\r"
expect "sftp> "
send "quit\r"

如果我用我的数组试试这个:

/path/to/script/expect.sh ${files[@]}

Expect 脚本仅上传数组中的第一个文件。

我想,我也必须在我的 expect 脚本中初始化一个数组。但我不知道如何用文件初始化和填充它,从我的 bash 脚本中的另一个数组通过管道传输到脚本。

提前致谢

马克

您可能想遍历列表中的每个文件

#!/usr/bin/expect

set files [lindex $argv 0]

spawn sftp user@destination.com
expect "Password:"
send "password\r"
for file in $files
do
  send "put $file\r"
  expect "sftp> "
done
expect "sftp> "
send "quit\r"

首先,您需要使用 /path/to/script/expect.sh "${files[@]}" 调用 expect 脚本,以便正确转义文件数组(参见 Bash FAQ 005)。

而且我不知道你为什么要给 expect 脚本一个 sh 扩展名,而它不是 shell 脚本……这是很误导人的。有很好的论据表明在可执行文件上没有 任何 扩展名,无论是二进制文件还是脚本,但这是偏离主题的观点。

您当前的 expect 脚本明确只上传第一个参数的文件,无论还有多少个参数。您想使用 foreach 遍历所有参数并全部上传:

#!/usr/bin/expect -f

spawn sftp user@destination.com
expect "Password:"
send "password\r"
foreach file $argv {
    expect "sftp> "
    send "put \"[string map {\" \\"} $file]\"\r"
}
expect "sftp> "
send "quit\r"

注意将文件名括起来放在引号中以避免名称中出现空格或其他不常见字符的问题(以及文件名中的转义引号)——与 shell 中的数组扩展的原因相同应该用引号引起来。