I've written a bash Script which moves, copies and renames some files. After this, it loads a list files in to an array.
And now, I want to pass the array to my expect script, which will upload the files over SFTP to a destination.
With a file in a single variable, i do this:
/path/to/script/expect.sh $file
Which works fine with this expect script:
#!/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"
If I try this with my array:
/path/to/script/expect.sh ${files[@]}
The Expect script uploads only the first file from the array.
I guess, I have to initialise an array in my expect script as well. But I don't know how to initialise and fill it with the files, piped to the script from the other array in my bash script.
Thanks in advance
marc
First off, you need to call your expect script with /path/to/script/expect.sh "${files[@]}"
so the files array is properly escaped (See Bash FAQ 005).
And I don't know why you'd give an expect script a sh extension when it's not a shell script... that's pretty misleading. There are good arguments to not have any extension on an executable, be it binary or script, but that's straying off topic into opinions.
Your current expect script explicitly only uploads the file that is the first argument, no matter how many more there are. You want to loop through all the arguments with foreach
and upload them all:
#!/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"
Note enclosing the filename to put in quotes to avoid issues with spaces or other unusual characters in the name (As well as escaping quotes in the filename) -- the same reason the array expansion in the shell should be enclosed in quotes.