• Time to read less than 1 minute

Copying a directory recursively on a Linux machine is easy with the following command:

cp -rap /source/dir /target/dir

The -r option triggers the recursive copy. The -a option will copy hidden files, and the -p option will preserve the file and folder permissions.

When the exclusion of subdirectories during the copy is needed, the cp commands can become quite restrictive. In this case, a better alternative is the rsync command which offers a simple and friendlier syntax:

rsync -av /source/dir /target/dir --exclude excluded/subdir

Here again, the -a option is for hidden files. The -v option is a shortcut for the --verbose option, which outputs result of the process in the console. The --exclude option allows to specify the subdirectory to exclude, and can be chained:

rsync -av /source/dir /target/dir --exclude excluded/subdir1 --exclude excluded/subdir2

Note that the --exclude option takes a path relative to the parent directory being copied, and not an absolute path.