Copy File/Directory

Cp Command

cp stands for copy. It’s used to copy files or groups of files or directories. It creates an exact image of a file on a disk with a different filename.

Syntax

cp [Options] Source Destination

Copy Files

The most basic scenario of using cp is to copy a file in the current working directory.

Example 1

To copy a file named file.txt to new_file.txt, enter the following.

cp file.txt new_file.txt

If the destination file doesn’t exist, the system creates it. But if it exists, then it’s simply overwritten without any warning.

Example 2

You can use the -i option to warn the user before overwriting the destination file. This will prompt for a response and if you press y, it overwrites the file.

cp -i file.txt new_file.txt

Example 3

You can copy a file to a directory. To copy a file named file.txt to a directory called newDir, where both file.txt and newDir reside in the current directory, follow the below syntax.

cp file.txt newDir

To copy files and directories, you must have at least read permissions on the source file and write permission on the destination directory. If you would like to copy files file1.txt, file2.txt, and file3.txt to newDir directory, type the following.

cp file1.txt file2.txt file3.txt newDir

Copy Directories

To copy a directory to another directory, you can use the cp command with flag -r.

Syntax

cp -r Source Destination

Example

cp -r oldDir backupDir