Skip to content
Advertisement

scp a folder to a remote system keeping the directory layout

I have a large directory tree with hundreds of nested sub-folders. I need to copy only 4 folders and their contents to a remote system, but I need to destination folder structure to be kept the same.

E.G.

JavaScript

I want to copy ./test/sub1/subsub1/* to a target such as user@system:~/test/sub1/subsub1/* but I do not want to copy subsub2 or sub2.

I have tried using scp as follows:

JavaScript

The result: scp: /test/sub1/subsub1: No such file or directory

I also tried:

JavaScript

This works, but dumps all the files into a single directory. The /test/sub1/subsub1 directory structure is not maintained.

How can I copy a folder, whilst maintaining its structure?

Advertisement

Answer

You need a two-pass solution. First, ensure the target directory exists on the remote host:

JavaScript

Then, you can copy your files. I recommend using rsync instead of scp, since it’s designed for syncing directories. Example usage:

JavaScript

The -e flag accepts a remote shell to use to carry out the transfer. Trailing slashes are very important with rsync, so make sure yours match the example above.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement