user1551817
user1551817

Reputation: 7451

scp multiple files in a shell script

I have a list of directory names.

I want to scp into a remote machine, go into each of my directory names and copy a file back to my local computer.

I so far have:

while read line
    do
        scp remote_machine:/home/$line/$line.dat ./local
    done < file_with_directory_names.txt

I have authorisation keys set up so that I don't have to enter the password each time - but this method does login to the remote machine for every file it transfers. I imagine that there is a much better way than this.

Upvotes: 0

Views: 981

Answers (1)

Mark Reed
Mark Reed

Reputation: 95242

You can specify multiple files in a single scp argument by separating them with spaces; you just need to make sure it's one argument to scp itself. This should work in your case:

scp "remote_machine:$(
    sed 's,.*,/home/&/&.dat,' file_with_directory_names.txt | xargs)" ./local

The sed command sticks the /home/ prefix and name.dat suffix on each line; the xargs outputs all the resulting pathnames on a single line separated by spaces. Plug that all into the source argument after the remote_machine: part, all inside double quotes so it's still a single argument to scp, and you're good to go.

Upvotes: 4

Related Questions