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.
./test/sub1/subsub1/hello.txt ./test/sub1/subsub2/hello2.txt ./test/sub2/hello3.txt
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:
scp -r ./test/sub1/subsub1 me@my-system:~/test/sub1/subsub1
The result: scp: /test/sub1/subsub1: No such file or directory
I also tried:
scp -r ./test/sub1/subsub1 me@my-system:~/test
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:
ssh me@my-system 'mkdir -p ~/test/sub1/subsub1'
Then, you can copy your files. I recommend using rsync
instead of scp
, since it’s designed for syncing directories. Example usage:
rsync -r -e ssh ./test/sub1/subsub1/ me@my-system:~/test/sub1/subsub1
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.