代码之家  ›  专栏  ›  技术社区  ›  PiMathCLanguage

如何在expect程序中为spawn命令编写多行?

  •  1
  • PiMathCLanguage  · 技术社区  · 8 年前

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

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

    在开始时得到相同的错误。

    如何在多行中写入文件,以使程序正常工作?我需要这个来提高choosen文件的可读性。

    编辑: 仅将本地用户名更改为user\u local

    3 回复  |  直到 7 年前
        1
  •  2
  •   pynexj    8 年前

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

    % puts "abc\
            def"
    abc def
    % puts {abc\
            def}
    abc def
    %
    
        2
  •  2
  •   Colin Macleod    8 年前

    假设文件名确实更长(否则就没什么意义了),您可以使用以下几个变量:

    #! /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
    
        3
  •  0
  •   PiMathCLanguage    7 年前

    对于任何只想使用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
    
    推荐文章