cp command is used in Linux to copy files and directories in terminal mode. 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 destination_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 destination_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 destination_directory
Note: destination should be a directory name
cp –i test.txt test1.txt test2.txt test3.txt /archive
Copy recursively – copy 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 –R directory_one/directory_two /directory_three/directory_four
cp –R 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 test3 directory with all its content.
Copy files using wildcard character
Wildcard character can also be used along with cp command. This can be used for copying all files in a directory or files with particular extension etc
Copy all files a directory to another directory
cp * /test
Copy all pdf files in folder to another location
cp *.pdf /test