Copy Directory with SSH — Three Methods

As a server admin, even simple tasks can benefit from a fresh perspective. To that end, today’s article talks about multiple ways you can copy an entire directory and its contents in linux. To do so, we’ll be exploring three commands: cp, scp, and rsync.

cp

You can copy files and directories within the same file system with the cp command. The -r argument tells cp that you wish to copy a directory recursively, which copies the directory’s contents as well. For instance:

cp -r /path/to/source/directory /path/to/destination/directory

The result is that the directory, including all of its contents and subdirectories, will be copied to a different directory on the local server.

scp

Meanwhile, the scp command will allow you to copy files and directories using an SSH encrypted connection. This allows for greater security and data integrity, and is commonly used to copy directories between remote servers, although it can also be used locally. To copy an entire directory using scp, you can also use the -r flag the same way you did with the cp command. Example:

scp -r /path/to/source/directory user@remotehost:/path/to/destination/directory

The result here is that the directory “directory” will be copied securely to the destination folder on “remotehost”

rsync

The rsync command enables you to replicate files and directories while keeping ownership and permissions. It also offers extra capabilities like compression and incremental updates. The -a switch enables “archive” mode, which allows you to use rsync to transfer a directory while preserving ownership and rights. For instance:

rsync -a /path/to/source/directory /path/to/destination/directory

This example shows how to use rsync to copy directories on the local machine. You can also use it the same way shown for scp if you want to use rsync to copy directories to remote servers.

That’s it!

The above is one of the more basic and common ways to use these commands. We would encourage you to use linux man pages for each command in order to learn about their more advanced features.

In conclusion, it is helpful for a server administrator to be able to copy a complete directory and all of its contents using a variety of techniques. For copying files and directories, the cp, scp, and rsync commands offer specific options and features; depending on your circumstance, one may be preferable to the others.