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?
To copy a directory (and all the files it contains), use scp with the -r option. This tells scp to recursively copy the source directory and its contents. You'll be prompted for your password on the source system ( deathstar.com ). The command won't work unless you enter the correct password.
The Unix command scp (which stands for "secure copy protocol") is a simple tool for uploading or downloading files (or directories) to/from a remote machine.
The scp tool relies on SSH (Secure Shell) to transfer files, so all you need is the username and password for the source and target systems. Another advantage is that with SCP you can move files between two remote servers, from your local machine in addition to transferring data between local and remote machines.
The scp command copies files or directories between a local and a remote system or between two remote systems. You can use this command from a remote system (after logging in with the ssh command) or from the local system. The scp command uses ssh for data transfer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With