Copy command for directories in Linux

 Tue, 08 Nov 2022 09:37 UTC

Copy command for directories in Linux
Image: CC BY 4.0 by cybrkyd


This tutorial covers the basic usage of the cp command for copying directories in Linux. It contains examples of copying single directories, multiple directories and directories containing spaces in their names.

What is the cp command?

cp is a command-line utility for copying files and directories from one place to another. It supports copying one or more files and directories and provides various options as well as the flexibility to batch-copy. Unlike the mv command, cp leaves the original file unchanged. The cp command is particularly useful for large copy jobs or tasks where multiple files and directories need to be copied.

How to copy a directory with cp

By default, the cp command will only copy files. It will return an error if attempting to copy a directory without specifying that the source is, in fact, a directory.

To copy a directory, the cp command must contain the options -r or -a. These options instruct cp to copy recursively from a source directory to a new destination. In the following examples, directory1 and all its contents will be copied into directory2:

$ cp -r directory1 directory2

Using the -a option:

$ cp -a directory1 directory2

Copy multiple directories with cp

To copy multiple directories using the cp command, separate the source directories with a space followed by the destination at the end. In the following example, both directory1 and directory2 will be copied into NewDirectory as sub-folders:

$ cp -r directory1 directory2 NewDirectory

The new folder structure will be like this:

.
├── directory1
├── directory2
└── NewDirectory
    ├── directory1
    └── directory2

Directory names with spaces

Directory names containing spaces can be copied by enclosing the directory name in either single or double quotes in the command. In the following example, the directory My Docs is to be copied:

$ cp -r 'My Docs' NewDirectory

or…

$ cp -r "My Docs" NewDirectory

Some nuances when copying directories

Copying a single directory to another directory will work even if NewDirectory does not exist. The command will create NewDirectory and copy directory1 into the new destination:

$ cp -r directory1 NewDirectory

However, when copying multiple directories, if NewDirectory does not exist, the cp command will fail:

$ cp -r directory1 directory2 NewDirectory
cp: target 'NewDirectory' is not a directory

Workaround this by ensuring the destination directory exists beforehand. Alternatively, combine mkdir with cp in the same command:

$ mkdir NewDirectory && cp -r directory1 directory2 NewDirectory