cp is a utility used for copying files and folder from one location to another. There are 3 primary ways to use
cp functions varies depending on the type and number of arguments passed to it.
Arguments are both filenames:
When both arguments are filenames,
cpcopies the file at the first argument to the file at the second argument.
cp /home/kamstut/myfile.txt /home/kamstut/projects/project_1/myfile_copied.txt
/home/kamstut/myfile.txtis the source file and
/home/kamstut/projects/project_1/myfile_copied.txtis the destination file. If
cpwill overwrite it, without warning. If it does not already exist, a new file will be created, and the content copied over.
cpaccepts relative paths as arguments, as well as absolute paths.
In order to copy folders using
cp, we must use the
-Roption. When both arguments are directories,
cpcopies the directory in the first argument to the directory at the second argument.
cp -R /home/kamstut/other_files /home/kamstut/projects/project_1/
other_filesfolder is copied (with its contents) to
/home/kamstut/projects/project_1/other_files. In order to copy the contents of the
other_filesfolder, we must use a wildcard.
cp -R /home/kamstut/other_files/* /home/kamstut/projects/project_1/
Here, all files in the
other_filesfolder are copied to
/home/kamstut/projects/project_1/. In fact, in this situation, you do not even need to have the
cp /home/kamstut/other_files/* /home/kamstut/projects/project_1/
Two or more arguments:
When two or more arguments are passed to
cpcopies every file specified to the destination specified. The destination is the last argument.
cp /home/kamstut/myfile1.txt /home/kamstut/myfile2.txt /home/kamstut/projects/project_1/
myfile2.txtare copied to the desination
If we wanted to copy a directory to our destination as well, we would need to add the
cp -R /home/kamstut/myfile1.txt /home/kamstut/myfile2.txt /home/kamstut/other_files /home/kamstut/projects/project_1/
other_filesfolder are all copied to the destination
If we wanted to copy
myfile2.txt, and the contents of the
other_filesto the same destination, we would need to use a wildcard,
*to indicate we want to copy the files in
cp -R /home/kamstut/myfile1.txt /home/kamstut/myfile2.txt /home/kamstut/other_files/* /home/kamstut/projects/project_1/
The last argument must be a directory.