如何在 spawn 命令的 expect 程序中编写多行代码?

How can I write multiple lines in expect program for the spawn command?

我编写了这个小脚本,用于从我的远程服务器获取多个文件到我的主机:

#! /usr/bin/expect -f

spawn scp \
user@remote:/home/user/{A.txt,B.txt} \
/home/user_local/Documents
expect "password: "
send "somesecretpwd\r"
interact

这工作正常,但是当我想像这样在文件之间换行时:

user@remote:/home/user/{A.txt,\
B.txt} \

我收到以下错误:

scp: /home/user/{A.txt,: No such file or directory
scp: B.txt}: No such file or directory

我试过这个:

user@remote:"/home/user/{A.txt,\
B.txt}" \

得到:

bash: -c: line 0: unexpected EOF while looking for matching `"'
bash: -c: line 1: syntax error: unexpected end of file
cp: cannot stat 'B.txt}"': No such file or directory

或者这个:

"user@remote:/home/user/{A.txt,\
B.txt}" \

开始时出现同样的错误。

如何在多行中写入文件,但程序可以正常运行?我需要它来提高所选文件的可读性。

编辑: 仅将本地用户名更改为 user_local

在 Tcl(以及 Expect)中,\<NEWLINE><SPACEs> 将被转换为一个单一的 <SPACE>,因此您不能将不包含空格的字符串写入多行。

% puts "abc\
        def"
abc def
% puts {abc\
        def}
abc def
%

假设文件名确实更长(否则意义不大),您可以使用如下几个变量:

#! /usr/bin/expect -f

set A A.txt
set B B.txt

spawn scp \
user@remote:/home/user/{$A,$B} \
/home/user/Documents
expect "password: "
send "somesecretpwd"
interact

对于任何想仅使用 expect 来解决类似问题的人:

您可以写一个文件列表,然后将所有文件连接成一个字符串。

代码如下:

#! /usr/bin/expect -f

set files {\ # a list of files
A.txt\
B.txt\
C.txt\
}

# will return the concatenated string with all files
# in this example it would be: A.txt,B.txt,C.txt
set concat [join $files ,]

# self made version of concat
# set concat [lindex $files 0] # get the first file
# set last_idx [expr {[llength $files]-1}] # calc the last index from the list
# set rest_files [lrange $files 1 $last_idx] # get other files
# foreach file $rest_files {
#     set concat $concat,$file # append the concat varibale with a comma and the other file
# }
# # puts "$concat" # only for testing the output

spawn scp \
user@remote:/home/doublepmcl/{$concat} \
/home/user_local/Documents
expect "password: "
send "somesecretpwd\r"
interact