簡體   English   中英

將包含文件列表的數組傳遞給期望腳本

[英]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 腳本中的另一個數組通過管道傳輸到腳本。

提前致謝

馬克

首先,您需要使用/path/to/script/expect.sh "${files[@]}"調用 expect 腳本,以便正確轉義文件數組(參見Bash FAQ 005 )。

而且我不知道為什么當 expect 腳本不是 shell 腳本時,你會給它一個 sh 擴展名……這是非常誤導的。 有很好的 arguments 可以在可執行文件上沒有任何擴展,無論是二進制文件還是腳本,但這是偏離主題的觀點。

您當前的 expect 腳本明確地只上傳作為第一個參數的文件,無論還有多少。 你想用foreach所有 arguments 並上傳它們:

#!/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"

請注意將文件名括在引號中,以避免名稱中出現空格或其他不尋常字符的問題(以及文件名中的 escaping 引號)——這與 shell 中的數組擴展應括在引號中的原因相同。

您可能想遍歷列表中的每個文件

#!/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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM