Quick Links

A common problem when working with files is applying operations recursively, or to every sub-directory in the entire folder. The scp utility is used to transfer files and directories to remote servers, and supports recursive operations.

Running scp Recursively

While it is sometimes faster for large transfers to be done in a single archive known as a tarball, most of the time the overhead of transferring individual files doesn't matter.

Copying recursively with scp is easy: simply use the -r flag in addition to anything else you had added:

scp -r localpath user@remote:/remotepath

Note that this is explicitely lowercase -r, unlike a lot of other commands that use or require -R.

This will act like a drag and drop into /remotepath/, copying the contents of localpath/ to the remote and placing them in /remotepath/localpath/.

If you want to instead sync localpath/ and /remotepath/, you will have to transfer the folder to the parent folder of /remotepath/, the destination. In this case, that would be /, the root directory.

This also will follow symbolic links in the local path when resolving files, but will not necessarily create those same links on the remote server. For example, copying a brand new file to and from /etc/nginx/sites-enabled will not automatically place it in /etc/nginx/sites-available on the remote.

Using rsync Instead

Linux has multiple tools to handle this job, and one of the better ones is rsync, which does everything scp can do, but has many more options and is much faster to boot. It also doesn't copy files that haven't been changed, making it a great tool for continously "syncing" two directories to each other without re-transferring data unnecessarily.

rsync works basically the same as scp, with a few more options included to specify the settings:

rsync -a -essh localpath/ user@remote:/remotepath/

The -a flag specifies archive mode, which turns on a lot of commonly used options all at once. The -e ssh flag sets up rsync to transfer over SSH.

Related: How to Use rsync to Backup Your Data on Linux