The cp command

Yaser Rahmati | یاسر رحمتی

The cp is a command-line utility for copying files and directory. cp stands for copy. This command is used to copy files or group of files or directory. It creates an exact image of a file on a disk with different file name. The cp command requires at least two filenames in its arguments.

Examples:

  • To copy the contents of the source file to the destination file.

cp sourceFile destFile

If the destination file doesn't exist then the file is created and the content is copied to it. If it exists then the file is overwritten.

  • To copy a file to another directory specify the absolute or the relative path to the destination directory.

cp sourceFile /folderName/destFile
  • To copy a directory, including all its files and subdirectories

cp -R folderName1 folderName2

The command above creates the destination directory and recursively copies all files and subdirectories from the source to the destination directory.

If the destination directory already exists, the source directory itself and its content are copied inside the destination directory.

  • To copy only the files and subdirectories but not the source directory

cp -RT folderName1 folderName2

Exercise

[root@academy tmp]# ls
[root@academy tmp]# mkdir folder1 folder2 folder3
[root@academy tmp]# ls
folder1  folder2  folder3
[root@academy tmp]# cd folder1
[root@academy folder1]# touch file1.txt file2.txt
[root@academy folder1]# ls
file1.txt  file2.txt
[root@academy folder1]# cd ..
[root@academy tmp]# cp folder1/file1.txt folder2
[root@academy tmp]# ls folder2
file1.txt
[root@academy tmp]# cp -R folder1 folder3
[root@academy tmp]# ls folder3
folder1
[root@academy tmp]# cp -RT folder1 folder3
[root@academy tmp]# ls folder3
file1.txt  file2.txt  folder1
[root@academy tmp]#

Syntax:

The general syntax for the cp command is as follows:

cp [OPTION] SOURCE DESTINATION
cp [OPTION] SOURCE DIRECTORY
cp [OPTION] SOURCE-1 SOURCE-2 SOURCE-3 SOURCE-n DIRECTORY

The first and second syntax is used to copy Source file to Destination file or Directory. The third syntax is used to copy multiple Sources(files) to Directory.

Some useful options

  • -i (interactive) i stands for Interactive copying. With this option system first warns the user before overwriting the destination file. cp prompts for a response, if you press y then it overwrites the file and with any other option leave it uncopied.

[root@academy tmp]# cp -i file1.txt file2.txt
cp: overwrite ‘file2.txt’?
[root@academy tmp]#
  • -b(backup) : With this option cp command creates the backup of the destination file in the same folder with the different name and in different format.

[root@academy tmp]# ls
a.txt  b.txt
[root@academy tmp]# cp -b a.txt b.txt
cp: overwrite ‘b.txt’? y
[root@academy tmp]# ls
a.txt  b.txt  b.txt~
[root@academy tmp]#

Additional Flags and their Functionalities:

Last updated