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.

  1. Arguments are both filenames:

    When both arguments are filenames, cp copies 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

    Here, /home/kamstut/myfile.txt is the source file and /home/kamstut/projects/project_1/myfile_copied.txt is the destination file. If /home/kamstut/projects/project_1/myfile_copied.txt already exists, cp will overwrite it, without warning. If it does not already exist, a new file will be created, and the content copied over.

    cp accepts relative paths as arguments, as well as absolute paths.

  2. Copying directories:

    In order to copy folders using cp, we must use the -R option. When both arguments are directories, cp copies 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_files folder is copied (with its contents) to /home/kamstut/projects/project_1/other_files. In order to copy the contents of the other_files folder, we must use a wildcard.

    cp -R /home/kamstut/other_files/* /home/kamstut/projects/project_1/

    Here, all files in the other_files folder are copied to /home/kamstut/projects/project_1/. In fact, in this situation, you do not even need to have the -R option.

    cp /home/kamstut/other_files/* /home/kamstut/projects/project_1/
  3. Two or more arguments:

    When two or more arguments are passed to cp, cp copies 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.txt and myfile2.txt are 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 -R flag.

    cp -R /home/kamstut/myfile1.txt /home/kamstut/myfile2.txt /home/kamstut/other_files /home/kamstut/projects/project_1/

    Here, myfile1.txt, myfile2.txt and the other_files folder are all copied to the destination /home/kamstut/projects/project_1/.

    If we wanted to copy myfile1.txt, myfile2.txt, and the contents of the other_files to the same destination, we would need to use a wildcard, * to indicate we want to copy the files in other_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.