How to copy files in Linux – cp command

cp command is used in Linux to copy files and directories. This is one of the basic commands of excel and you may need it every now and then.
Syntax

cp [option] source destination

Option is various switches available with cp command.

Copy file in same directory

Here source and destination directory of file to be copied is same.

Syntax

cp original_file copy_file

Note: if copied file name already exist in the folder it will be overwritten.

Example

cp test.txt test1.txt

Interactive copy of file

Copy file with –i switch. –i switch is for interactive copy command where you will be prompted if file with same name exist in destination location. You will have to input “yes” to overwrite file, writing anything else will abort the command.

Syntax

cp –i original_file copy_file

Example

cp –i test.txt test1.txt

Copy files to another directory

To copy files to another directory use cp command with source file name and destination directory name.
Syntax

cp –i file_source desitnation_directory

Example

cp –i test.txt /archive

Copy files to another directory and change name of file

To copy files to another directory use cp command with source file name and destination directory name along with new name of file.

 

Syntax

cp –i file_source desitnation_directory/new_file_name

 

Example
 cp –i test.txt  /archive/test1.txt

Copy multiple files to a directory

To copy more than one file to another directory, you can use cp command with name of files in sequence one after other.

Syntax

cp –i file_one file_two file_three file_so_on desitnation_directory

Note: destination should be a directory name

Example

cp –i test.txt test1.txt test2.txt test3.txt /archive

Copy recursively –complete directory structure into another directory

cp command can be used to files recursively i.e. complete entire directory structure to another directory. This can be achieved by using –R switch.

Syntax

cp –i directory_one/directory_two /directory_three/directory_four

Example

cp –i test1/test2 /test3/test4

Here cp command requires that test3 directory exists else command will fail to execute. Result of above command is test2 directory will be created in test4 directory with all its content.