cp
cp is a utility used for copying files and folder from one location to another. There are 3 primary ways to use cp. How 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.txtHere,
/home/kamstut/myfile.txtis the source file and/home/kamstut/projects/project_1/myfile_copied.txtis the destination file. If/home/kamstut/projects/project_1/myfile_copied.txtalready exists,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. -
Copying directories:
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/Here, the
other_filesfolder is copied (with its contents) to/home/kamstut/projects/project_1/other_files. In order to copy the contents of theother_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-Roption.cp /home/kamstut/other_files/* /home/kamstut/projects/project_1/ -
Two or more arguments:
When two or more arguments are passed to
cp,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/Here,
myfile1.txtandmyfile2.txtare copied to the desination/home/kamstut/projects/project_1/.If we wanted to copy a directory to our destination as well, we would need to add the
-Rflag.cp -R /home/kamstut/myfile1.txt /home/kamstut/myfile2.txt /home/kamstut/other_files /home/kamstut/projects/project_1/Here,
myfile1.txt,myfile2.txtand theother_filesfolder are all copied to the destination/home/kamstut/projects/project_1/.If we wanted to copy
myfile1.txt,myfile2.txt, and the contents of theother_filesto the same destination, we would need to use a wildcard,*to indicate we want to copy the files inother_files.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.
When copying files, if you want to keep the permissions and the last modified date the same, use the -p option like this: cp -p myfile.txt somedirectory