Copying files (cp command)

Use the cp command to create a copy of the contents of the file or directory specified by the SourceFile or SourceDirectory parameters into the file or directory specified by the TargetFile or TargetDirectory parameters.

If the file specified as the TargetFile exists, the copy writes over the original contents of the file without warning. If you are copying more than one SourceFile, the target must be a directory.

If a file with the same name exists at the new destination, the copied file overwrites the file at the new destination. Therefore, it is a good practice to assign a new name for the copy of the file to ensure that a file of the same name does not exist in the destination directory.

To place a copy of the SourceFile into a directory, specify a path to an existing directory for the TargetDirectory parameter. Files maintain their respective names when copied to a directory unless you specify a new file name at the end of the path. The cp command also copies entire directories into other directories if you specify the -r or -R flags.

You can also copy special-device files using the -R flag. Specifying -R causes the special files to be re-created under the new path name. Specifying the -r flag causes the cp command to attempt to copy the special files to regular files.

The following are examples of how to use the cp command:
  • To make a copy of a file in the current directory, type the following:
    cp prog.c prog.bak
    This copies prog.c to prog.bak. If the prog.bak file does not already exist, then the cp command creates it. If it does exist, then the cp command replaces it with a copy of the prog.c file.
  • To copy a file in your current directory into another directory, type the following:
    cp jones /home/nick/clients
    This copies the jones file to /home/nick/clients/jones.
  • To copy all the files in a directory to a new directory, type the following:
    cp /home/janet/clients/* /home/nick/customers
    This copies only the files in the clients directory to the customers directory.
  • To copy a specific set of files to another directory, type the following:
    cp jones lewis smith /home/nick/clients
    This copies the jones, lewis, and smith files in your current working directory to the /home/nick/clients directory.
  • To use pattern-matching characters to copy files, type the following:
    cp programs/*.c .
    This copies the files in the programs directory that end with .c to the current directory, indicated by the single dot (.). You must type a space between the c and the final dot.