cp command is used in Linux to copy files and directories. This is one of the basic commands in Linux and you may need it every now and then to copy files in Linux.
cp [option] source destination
Option is various switches available with cp command.
Linux cp command with example
Copy file in same directory using cp command in Linux terminal
Using this command you can copy files within same directory in Linux terminal. Here source and destination directory of file to be copied is same.
cp original_file copy_file
Note: if copied file name already exist in the folder it will be overwritten.
cp test.txt test1.txt
Interactive copy of file in Linux terminal
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.
cp –i original_file copy_file
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.
cp –i file_source desitnation_directory
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.
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.
cp –i file_one file_two file_three file_so_on desitnation_directory
Note: destination should be a directory name
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.
cp –i directory_one/directory_two /directory_three/directory_four
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.