Copy command for files in Linux

 Sun, 06 Nov 2022 07:22 UTC

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


How to copy files using the cp command

This tutorial details the basic usage of the cp command for copying files in Linux. It contains examples of copying single files, multiple files and files 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.

Copy a file with cp

To copy a file, enter the name of the file to be copied and then the destination.

$ cp SOURCE DEST

For example, to create a copy of aa.txt called bb.txt in the same directory:

$ cp aa.txt bb.txt

Note: the destination file-name needs to be specified if copying in the same directory.

Copy a file between directories with cp

The following example will copy the file aa.txt from the current directory to another directory:

$ cp aa.txt ~/Documents/folder 

To copy a file from one directory to another, specify the location of both the source file and destination in the command. To copy the file aa.txt from the directory ~/Documents/folder to the directory ~/Documents/subfolder:

$ cp ~/Documents/folder/aa.txt ~/Documents/subfolder 

In both examples above, notice that no file name was specified for the destination. The result is that a copy of the file aa.txt will be added to the respective destination folder and will keep the same name. You can specify a new name of the copied file:

$ cp aa.txt ~/Documents/folder/aa-copy.txt

or…

$ cp ~/Documents/folder/aa.txt ~/Documents/subfolder/aa-copy-2.txt

Copy multiple files with cp

To copy multiple files using the cp command, separate the source files with a space. In the following example, the three files xx.txt, yy.txt and zz.txt will be copied:

$ cp xx.txt yy.txt zz.txt ~/Documents/folder

cp also allows for pattern matching to achieve the same result:

$ cp *.txt ~/Documents/folder

File names with spaces

File-names containing spaces can be copied by enclosing the file-name in either single or double quotes in the command. In the following example, the file my spaced file.txt is to be copied:

$ cp 'my spaced file.txt' ~/Documents/folder

or…

$ cp "my spaced file.txt" ~/Documents/folder