Linux Commands

How to Copy Remote Files Recursively in Linux

When you need to copy remote files in Linux, two popular command-line tools can get the job done for you — i.e., scp and rsync. This tutorial will describe how to use the scp and rsync tools to copy remote files recursively in Linux.

Prerequisite

A working SSH configuration.

Copy remote files recursively with scp

Scp is an acronym for Secure Copy. The scp tool is used to securely copy files to and from a remote computer using the secure shell protocol (SSH.)

The basic syntax of the scp command is as follows.

scp <option> <source> <destination>

To recursively copy files, you would need to use the -r option.

For example, the command below will recursively copy the content of my /projects directory to a /backup directory on the remote server. A valid username on the remote server is required.

$ scp -r /projects redhat8@20.68.114.222:/backup

Figure 1 – Copy files recursively to a remote server with scp

Here is another example to recursively copy the content of the /backup/projects directory from the remote server to a directory on my local machine.

$ scp -r redhat8@20.68.114.222:/backup/projects /recovered

Figure 2 – Copy files recursively from a remote server with scp

Copy remote files recursively with rsync

The rsync tool (Remote Sync) is used to copy (synchronize) files between local or remote computers. Rsync also uses SSH to communicate. The basic syntax of the rsync command is as follows.

rsync <options> <source <destination>

The option to recursively copy files is denoted by -r.

Other recommended options include:

-a which preserves the properties of the copied files

-v which displays a detailed output

One very good thing about rsync is that it compares the source and destination directories, and it copies only the differences. This feature reduces network data usage, and it makes rsync a good tool for mirroring and backing up data.

Below is an example to recursively copy the content of my /projects2 directory to a /backup2 directory on the remote server. A valid username on the remote server is required.

rsync -rav /projects2 redhat8@20.68.114.222:/backup2

Figure 3 – Copy files recursively to a remote server with rsync

The next example recursively copies the/backup2/projects2 directory content from the remote server to a directory on my local machine.

rsync -rav redhat8@20.68.114.222:/backup2/projects2 /recovered2

Figure 4 – Copy files recursively from a remote server with rsync

Conclusion

This tutorial showed you how to copy files recursively in Linux by using the scp and rsync tools. Let us know what you think.

About the author

Karim Buzdar

Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. He blogs at LinuxWays.