Copy a directory

Written by on .

Using cp (POSIX)

The following command is used to copy a directory from one place to another:

cp -aTu /path/to/directory-1/ /path/to/directory-2/

Using ssh and tar

In order to copy a local directory onto another machine, using ssh:

tar cf - /path/to/directory-1/ | ssh -T -p 22 username@example.com tar xfC - /path/to/directory-2/

Or similarly, to copy a remote directory to a local machine:

ssh -T -p 22 username@example.com tar cf - /path/to/directory-1/ | tar xfC - /path/to/directory-2/

Using rsync

If either the source or target directory is on another machine, you may transfer it over an ssh tunnel, using rsync.

rsync -aAX -P -c -e "ssh -p 22" --inplace --no-whole-file /path/to/directory-1/ username@example.com:/path/to/directory-2/

In order to synchronize, instead of copying, add --delete. This makes rsync delete files in the target directory, that do not exist in the source directory.

For local file transfers, not over a network connection, use:

rsync -aAX -P -c /path/to/directory-1/ /path/to/directory-2/

Using sshfs

This allows any copy utility to be used for any remote location accessible by ssh, including cp. It works by mounting a remote directory into a local mount point. Under the hood it uses FUSE for the filesystem integration, and SFTP for the actual transfer.

The following copies the local contents of /path/to/directory-1/ into the remote directory /path/to/directory-2/.

mkdir /tmp/remote sshfs -p 22 username@example.com:/path/to/directory-2/ /tmp/remote/ cp -a /path/to/directory-1/ /mnt/remote/ umount /tmp/remote && rmdir /tmp/remote

Whereas the following copies the directory itself, like so: /path/to/directory-2/directory-1/.

mkdir /tmp/remote sshfs -p 22 username@example.com:/path/to/ /tmp/remote/ cp -a /path/to/directory-1/ /mnt/remote/directory-2/ umount /tmp/remote && rmdir /tmp/remote